Create an array of specific type depending on condition The 2019 Stack Overflow Developer Survey Results Are InHow to create a generic array in Java?Create ArrayList from arrayFastest way to determine if an integer's square root is an integerHow do I generate random integers within a specific range in Java?How do I make the method return type generic?How can I create an executable JAR with dependencies using Maven?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?Creating a memory leak with JavaWhy is it faster to process a sorted array than an unsorted array?How to Convert a Java 8 Stream to an Array?
What does もの mean in this sentence?
What is the meaning of Triage in Cybersec world?
What do I do when my TA workload is more than expected?
Short story: man watches girlfriend's spaceship entering a 'black hole' (?) forever
Why does the nucleus not repel itself?
A word that means fill it to the required quantity
Is an up-to-date browser secure on an out-of-date OS?
Variable with quotation marks "$()"
Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?
Pokemon Turn Based battle (Python)
How do you keep chess fun when your opponent constantly beats you?
What does Linus Torvalds mean when he says that Git "never ever" tracks a file?
A female thief is not sold to make restitution -- so what happens instead?
How much of the clove should I use when using big garlic heads?
The phrase "to the numbers born"?
Why can't wing-mounted spoilers be used to steepen approaches?
How to add class in ko template in magento2
Match Roman Numerals
Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?
Why can I use a list index as an indexing variable in a for loop?
"as much details as you can remember"
Getting crown tickets for Statue of Liberty
Falsification in Math vs Science
Likelihood that a superbug or lethal virus could come from a landfill
Create an array of specific type depending on condition
The 2019 Stack Overflow Developer Survey Results Are InHow to create a generic array in Java?Create ArrayList from arrayFastest way to determine if an integer's square root is an integerHow do I generate random integers within a specific range in Java?How do I make the method return type generic?How can I create an executable JAR with dependencies using Maven?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?Creating a memory leak with JavaWhy is it faster to process a sorted array than an unsorted array?How to Convert a Java 8 Stream to an Array?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have a switch case on some enum
type depending on which I am creating an array.
It looks like:
switch (type)
case BOOLEAN:
Boolean[] booleans = new Boolean[];
case STRING:
String[] strings = new String[];
I wonder is it possible to extract it to some method so it works like:
ArrayWrapper arrayWrapper = // some logic for which I am looking for
and then I have a generic method that accepts any type of array, and I would like to invoke it likemethod(arrayWrapper.getArray());
and it will be casted to specific type and processed by specific type processor?
java java-8 java-stream
add a comment |
I have a switch case on some enum
type depending on which I am creating an array.
It looks like:
switch (type)
case BOOLEAN:
Boolean[] booleans = new Boolean[];
case STRING:
String[] strings = new String[];
I wonder is it possible to extract it to some method so it works like:
ArrayWrapper arrayWrapper = // some logic for which I am looking for
and then I have a generic method that accepts any type of array, and I would like to invoke it likemethod(arrayWrapper.getArray());
and it will be casted to specific type and processed by specific type processor?
java java-8 java-stream
nope, not really. Arrays can't be of a generic type - you can declare one like that, but you can't create one.
– Eugene
Mar 8 at 11:12
1
Are you looking for anObject[]
there?
– Naman
Mar 8 at 11:26
1
Fully not sure what you're trying to do. (What's the relation to the "java-stream" tag?!) So you have an enum that defines which type of array you will create, so at that point you know what type the array is. Then you lose the information from the enum and later want to try and reconstruct it to basically do the sameswitch(type)
on the array instances again?
– JimmyB
Mar 8 at 11:45
add a comment |
I have a switch case on some enum
type depending on which I am creating an array.
It looks like:
switch (type)
case BOOLEAN:
Boolean[] booleans = new Boolean[];
case STRING:
String[] strings = new String[];
I wonder is it possible to extract it to some method so it works like:
ArrayWrapper arrayWrapper = // some logic for which I am looking for
and then I have a generic method that accepts any type of array, and I would like to invoke it likemethod(arrayWrapper.getArray());
and it will be casted to specific type and processed by specific type processor?
java java-8 java-stream
I have a switch case on some enum
type depending on which I am creating an array.
It looks like:
switch (type)
case BOOLEAN:
Boolean[] booleans = new Boolean[];
case STRING:
String[] strings = new String[];
I wonder is it possible to extract it to some method so it works like:
ArrayWrapper arrayWrapper = // some logic for which I am looking for
and then I have a generic method that accepts any type of array, and I would like to invoke it likemethod(arrayWrapper.getArray());
and it will be casted to specific type and processed by specific type processor?
java java-8 java-stream
java java-8 java-stream
edited Mar 18 at 15:13
fantaghirocco
3,83652738
3,83652738
asked Mar 8 at 11:11
Oleksandr RiznykOleksandr Riznyk
356213
356213
nope, not really. Arrays can't be of a generic type - you can declare one like that, but you can't create one.
– Eugene
Mar 8 at 11:12
1
Are you looking for anObject[]
there?
– Naman
Mar 8 at 11:26
1
Fully not sure what you're trying to do. (What's the relation to the "java-stream" tag?!) So you have an enum that defines which type of array you will create, so at that point you know what type the array is. Then you lose the information from the enum and later want to try and reconstruct it to basically do the sameswitch(type)
on the array instances again?
– JimmyB
Mar 8 at 11:45
add a comment |
nope, not really. Arrays can't be of a generic type - you can declare one like that, but you can't create one.
– Eugene
Mar 8 at 11:12
1
Are you looking for anObject[]
there?
– Naman
Mar 8 at 11:26
1
Fully not sure what you're trying to do. (What's the relation to the "java-stream" tag?!) So you have an enum that defines which type of array you will create, so at that point you know what type the array is. Then you lose the information from the enum and later want to try and reconstruct it to basically do the sameswitch(type)
on the array instances again?
– JimmyB
Mar 8 at 11:45
nope, not really. Arrays can't be of a generic type - you can declare one like that, but you can't create one.
– Eugene
Mar 8 at 11:12
nope, not really. Arrays can't be of a generic type - you can declare one like that, but you can't create one.
– Eugene
Mar 8 at 11:12
1
1
Are you looking for an
Object[]
there?– Naman
Mar 8 at 11:26
Are you looking for an
Object[]
there?– Naman
Mar 8 at 11:26
1
1
Fully not sure what you're trying to do. (What's the relation to the "java-stream" tag?!) So you have an enum that defines which type of array you will create, so at that point you know what type the array is. Then you lose the information from the enum and later want to try and reconstruct it to basically do the same
switch(type)
on the array instances again?– JimmyB
Mar 8 at 11:45
Fully not sure what you're trying to do. (What's the relation to the "java-stream" tag?!) So you have an enum that defines which type of array you will create, so at that point you know what type the array is. Then you lose the information from the enum and later want to try and reconstruct it to basically do the same
switch(type)
on the array instances again?– JimmyB
Mar 8 at 11:45
add a comment |
3 Answers
3
active
oldest
votes
Java Generics combined with the Reflection API can be used in order to obtain an instance of T[]
:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(Class<T> clazz, int size)
return (T[])Array.newInstance(clazz, size);
If you want to store, for any reason, a value in the resulting array:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(T obj)
T[] a = (T[])Array.newInstance(obj.getClass(), 1);//or whatever size you want
a[0] = obj;
return a;
See also: How to create a generic array in Java?
add a comment |
The java.lang.reflect.Array
class provides functionality for working with any type of arrays, without knowing what type it is.
Using that class, you can write code like this:
public void example(Class<?> elemType)
Object[] arr = (Object[]) Array.newInstance(elemType, 10);
// Do something with the array
(Don't cast to Object[]
if you want to be able to work with arrays of primitive types.)
Array
is part of the reflection system. That implies that you will have to used Class
objects for element types, and probably have variables of Object
type to refer to element values.
add a comment |
One possible way would be to bind the array's element type to a generic type parameter and tie the processor and the array together early on:
public class ArrayProcessingWrapper<T>
private final T[] array;
private final ArrayProcessor<T> processor;
public ArrayProcessingWrapper(T[] array, ArrayProcessor<T> processor)
super();
this.array = array;
this.processor = processor;
public void processArray()
this.processor.process(this.array);
Another way might be along the lines of functions
public abstract class Processor<T>
private final Supplier<T[]> arraySupplier;
public Processor(final Supplier<T[]> arraySupplier)
super();
this.arraySupplier = arraySupplier;
public T[] createArray()
return this.arraySupplier.get();
public void processNewArray()
this.doProcess(this.createArray());
protected abstract void doProcess(T[] data);
public class BooleanProcessor extends Processor<Boolean>
public BooleanProcessor(Supplier<Boolean[]> arraySupplier)
super(arraySupplier);
@Override
protected void doProcess(Boolean[] data)
// Do fancy boolean stuff...
But also have a look at Iterable<E>
and/or Collection<E>
(of which ArrayList<E>
is what behaves the most like an array) instead of arrays.
To me, it seems like a design flaw if you need to use different logic ("processors") depending on the (runtime) type of an array.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55061995%2fcreate-an-array-of-specific-type-depending-on-condition%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Java Generics combined with the Reflection API can be used in order to obtain an instance of T[]
:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(Class<T> clazz, int size)
return (T[])Array.newInstance(clazz, size);
If you want to store, for any reason, a value in the resulting array:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(T obj)
T[] a = (T[])Array.newInstance(obj.getClass(), 1);//or whatever size you want
a[0] = obj;
return a;
See also: How to create a generic array in Java?
add a comment |
Java Generics combined with the Reflection API can be used in order to obtain an instance of T[]
:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(Class<T> clazz, int size)
return (T[])Array.newInstance(clazz, size);
If you want to store, for any reason, a value in the resulting array:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(T obj)
T[] a = (T[])Array.newInstance(obj.getClass(), 1);//or whatever size you want
a[0] = obj;
return a;
See also: How to create a generic array in Java?
add a comment |
Java Generics combined with the Reflection API can be used in order to obtain an instance of T[]
:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(Class<T> clazz, int size)
return (T[])Array.newInstance(clazz, size);
If you want to store, for any reason, a value in the resulting array:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(T obj)
T[] a = (T[])Array.newInstance(obj.getClass(), 1);//or whatever size you want
a[0] = obj;
return a;
See also: How to create a generic array in Java?
Java Generics combined with the Reflection API can be used in order to obtain an instance of T[]
:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(Class<T> clazz, int size)
return (T[])Array.newInstance(clazz, size);
If you want to store, for any reason, a value in the resulting array:
@SuppressWarnings("unchecked")
public static <T> T[] createArrayInstance(T obj)
T[] a = (T[])Array.newInstance(obj.getClass(), 1);//or whatever size you want
a[0] = obj;
return a;
See also: How to create a generic array in Java?
edited Mar 8 at 13:16
answered Mar 8 at 12:41
fantaghiroccofantaghirocco
3,83652738
3,83652738
add a comment |
add a comment |
The java.lang.reflect.Array
class provides functionality for working with any type of arrays, without knowing what type it is.
Using that class, you can write code like this:
public void example(Class<?> elemType)
Object[] arr = (Object[]) Array.newInstance(elemType, 10);
// Do something with the array
(Don't cast to Object[]
if you want to be able to work with arrays of primitive types.)
Array
is part of the reflection system. That implies that you will have to used Class
objects for element types, and probably have variables of Object
type to refer to element values.
add a comment |
The java.lang.reflect.Array
class provides functionality for working with any type of arrays, without knowing what type it is.
Using that class, you can write code like this:
public void example(Class<?> elemType)
Object[] arr = (Object[]) Array.newInstance(elemType, 10);
// Do something with the array
(Don't cast to Object[]
if you want to be able to work with arrays of primitive types.)
Array
is part of the reflection system. That implies that you will have to used Class
objects for element types, and probably have variables of Object
type to refer to element values.
add a comment |
The java.lang.reflect.Array
class provides functionality for working with any type of arrays, without knowing what type it is.
Using that class, you can write code like this:
public void example(Class<?> elemType)
Object[] arr = (Object[]) Array.newInstance(elemType, 10);
// Do something with the array
(Don't cast to Object[]
if you want to be able to work with arrays of primitive types.)
Array
is part of the reflection system. That implies that you will have to used Class
objects for element types, and probably have variables of Object
type to refer to element values.
The java.lang.reflect.Array
class provides functionality for working with any type of arrays, without knowing what type it is.
Using that class, you can write code like this:
public void example(Class<?> elemType)
Object[] arr = (Object[]) Array.newInstance(elemType, 10);
// Do something with the array
(Don't cast to Object[]
if you want to be able to work with arrays of primitive types.)
Array
is part of the reflection system. That implies that you will have to used Class
objects for element types, and probably have variables of Object
type to refer to element values.
edited Mar 8 at 11:43
answered Mar 8 at 11:38
LiiLii
7,25144163
7,25144163
add a comment |
add a comment |
One possible way would be to bind the array's element type to a generic type parameter and tie the processor and the array together early on:
public class ArrayProcessingWrapper<T>
private final T[] array;
private final ArrayProcessor<T> processor;
public ArrayProcessingWrapper(T[] array, ArrayProcessor<T> processor)
super();
this.array = array;
this.processor = processor;
public void processArray()
this.processor.process(this.array);
Another way might be along the lines of functions
public abstract class Processor<T>
private final Supplier<T[]> arraySupplier;
public Processor(final Supplier<T[]> arraySupplier)
super();
this.arraySupplier = arraySupplier;
public T[] createArray()
return this.arraySupplier.get();
public void processNewArray()
this.doProcess(this.createArray());
protected abstract void doProcess(T[] data);
public class BooleanProcessor extends Processor<Boolean>
public BooleanProcessor(Supplier<Boolean[]> arraySupplier)
super(arraySupplier);
@Override
protected void doProcess(Boolean[] data)
// Do fancy boolean stuff...
But also have a look at Iterable<E>
and/or Collection<E>
(of which ArrayList<E>
is what behaves the most like an array) instead of arrays.
To me, it seems like a design flaw if you need to use different logic ("processors") depending on the (runtime) type of an array.
add a comment |
One possible way would be to bind the array's element type to a generic type parameter and tie the processor and the array together early on:
public class ArrayProcessingWrapper<T>
private final T[] array;
private final ArrayProcessor<T> processor;
public ArrayProcessingWrapper(T[] array, ArrayProcessor<T> processor)
super();
this.array = array;
this.processor = processor;
public void processArray()
this.processor.process(this.array);
Another way might be along the lines of functions
public abstract class Processor<T>
private final Supplier<T[]> arraySupplier;
public Processor(final Supplier<T[]> arraySupplier)
super();
this.arraySupplier = arraySupplier;
public T[] createArray()
return this.arraySupplier.get();
public void processNewArray()
this.doProcess(this.createArray());
protected abstract void doProcess(T[] data);
public class BooleanProcessor extends Processor<Boolean>
public BooleanProcessor(Supplier<Boolean[]> arraySupplier)
super(arraySupplier);
@Override
protected void doProcess(Boolean[] data)
// Do fancy boolean stuff...
But also have a look at Iterable<E>
and/or Collection<E>
(of which ArrayList<E>
is what behaves the most like an array) instead of arrays.
To me, it seems like a design flaw if you need to use different logic ("processors") depending on the (runtime) type of an array.
add a comment |
One possible way would be to bind the array's element type to a generic type parameter and tie the processor and the array together early on:
public class ArrayProcessingWrapper<T>
private final T[] array;
private final ArrayProcessor<T> processor;
public ArrayProcessingWrapper(T[] array, ArrayProcessor<T> processor)
super();
this.array = array;
this.processor = processor;
public void processArray()
this.processor.process(this.array);
Another way might be along the lines of functions
public abstract class Processor<T>
private final Supplier<T[]> arraySupplier;
public Processor(final Supplier<T[]> arraySupplier)
super();
this.arraySupplier = arraySupplier;
public T[] createArray()
return this.arraySupplier.get();
public void processNewArray()
this.doProcess(this.createArray());
protected abstract void doProcess(T[] data);
public class BooleanProcessor extends Processor<Boolean>
public BooleanProcessor(Supplier<Boolean[]> arraySupplier)
super(arraySupplier);
@Override
protected void doProcess(Boolean[] data)
// Do fancy boolean stuff...
But also have a look at Iterable<E>
and/or Collection<E>
(of which ArrayList<E>
is what behaves the most like an array) instead of arrays.
To me, it seems like a design flaw if you need to use different logic ("processors") depending on the (runtime) type of an array.
One possible way would be to bind the array's element type to a generic type parameter and tie the processor and the array together early on:
public class ArrayProcessingWrapper<T>
private final T[] array;
private final ArrayProcessor<T> processor;
public ArrayProcessingWrapper(T[] array, ArrayProcessor<T> processor)
super();
this.array = array;
this.processor = processor;
public void processArray()
this.processor.process(this.array);
Another way might be along the lines of functions
public abstract class Processor<T>
private final Supplier<T[]> arraySupplier;
public Processor(final Supplier<T[]> arraySupplier)
super();
this.arraySupplier = arraySupplier;
public T[] createArray()
return this.arraySupplier.get();
public void processNewArray()
this.doProcess(this.createArray());
protected abstract void doProcess(T[] data);
public class BooleanProcessor extends Processor<Boolean>
public BooleanProcessor(Supplier<Boolean[]> arraySupplier)
super(arraySupplier);
@Override
protected void doProcess(Boolean[] data)
// Do fancy boolean stuff...
But also have a look at Iterable<E>
and/or Collection<E>
(of which ArrayList<E>
is what behaves the most like an array) instead of arrays.
To me, it seems like a design flaw if you need to use different logic ("processors") depending on the (runtime) type of an array.
edited Mar 8 at 12:05
answered Mar 8 at 11:59
JimmyBJimmyB
9,63711838
9,63711838
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55061995%2fcreate-an-array-of-specific-type-depending-on-condition%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
nope, not really. Arrays can't be of a generic type - you can declare one like that, but you can't create one.
– Eugene
Mar 8 at 11:12
1
Are you looking for an
Object[]
there?– Naman
Mar 8 at 11:26
1
Fully not sure what you're trying to do. (What's the relation to the "java-stream" tag?!) So you have an enum that defines which type of array you will create, so at that point you know what type the array is. Then you lose the information from the enum and later want to try and reconstruct it to basically do the same
switch(type)
on the array instances again?– JimmyB
Mar 8 at 11:45