How to restrict ArrayList to accept only int,float and double values?
ArrayList<Integer,Float,Double> al=new ArrayList<<Integer,Float,Double>();
al.add(5);
al.add(5.6);
Create your custom class and use that in your ArrayList. Otherwise, by using for example Number, you'd end up with allowing more than those basic types.
you could use an ArrayList<Number> however this would include the following types:
AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short
You can use Number as Generc values:
ArrayList<Number> al=new ArrayList<Number>();
You can only achieve this at runtime by extending ArrayList and overriding all methods that add data. Then you will be able to check the class of any object added to your ArrayList and decide whether to throw an Exception or just silently reject.
I don't know your exact requirements, but the simplest way would be to just use an ArrayList<Double>. If you want to add 3 you would have to write add(3.0) or add((double) 3).
That wouldn't be exactly what you requested because the list wouldn't contain any Integer or Float objects.
We would need more information about your use case to be able to give the best answer.
Related
In order to complete one of my Java assignments, I have to do what seems like the impossible.
I have to create a method that takes in different stuff and plugs it into an array. We don't necessarily know what is being put into the array and thus the array must be able to accept Strings, Double, Integer, etc...
Of course, the obvious solution would be to use ArrayList<E> (i.e. a generic array). However, that's partly the complication of the problem. We cannot use an ArrayList, only a regular array. As far as I can find, when creating an array its intake value must be declared. Which leads me to believe that this assignment is impossible (yet I doubt the teacher would give me an impossible assignment).
Any suggestions?
You can always use an array of Object - Object[].
Object[] objects = new Object[2];
objects[0] = "ABC";
objects[1] = Integer.valueOf("15");
Are you sure you need a generic array or an array that can hold anything?
If the former, then create a class that will act as wrapper of Object[] array and use a <T> generic for type cast when getting the elements of the array, which is similar to the implementation of ArrayList class. If the latter, use Object[] directly.
Is it possible to set several object to List?
If I declare List<Object> it will accept any kind of objects.
If I declare List<Integer> it will accept only integers.
Can I make a list which will accept Integers OR Floats and nothing else?
Is it possible to set several object to List?
Yes you can do that by declaring list as List<Object>
Can i make a list wich will accept Integers OR Floats and nothing else?
There is no direct way to accept only two type.
Possible ways of doing it is
1) Take individual lists (preferred)
2) Take List of type Object. And use insatanceof key words while
using it.
3) Implementing your own list and override add() method. While
adding to that list check type of instance and if it is not desired,
throw Exception.
To simulate a list which can hold integer or float values I would probably use an "Either" type.
While java doesn't provide it automatically, stackoverflow can help with a good enough implementation:
How can I simulate Haskell's "Either a b" in Java
so you would have:
List<Either<Integer,Float>> list;
You can get a support from This tutorial, And you can read the java documentation as well.
There is a thread also here.
Well, this will be a very lame question, but ... how to convert List<Comparable<?>> to List<Comparable<Object>> and backwards? Is there any nicer way than this?
private List<Comparable<Object>> convertFromGeneric(List<Comparable<?>> list) {
List<Comparable<Object>> output = new ArrayList<Comparable<Object>>();
for(Comparable<?> el : list) {
output.add((Comparable<Object>) el);
}
return output;
}
Thanks in advance
The two types List<Comparable<Object>> and List<Comparable<?>> are not equivalent. The first is specifically a list of things that can be compared with Objects, while the second is a list of things that can each be compared to some mystery type you don't know.
This distinction is subtle but important: if I retrieve a Comparable<Object> from the list I can call compareTo("myString") on it, since a String is an Object; but if I have a Comparable<?> I can't call its compareTo method at all since for all I know it only compares integers, or floats, or PeanutButterSandwich instances. The upside is that the person who produced a List<Comparable<?>> could add a Comparable<Integer> and a Comparable<String> and a Comparable<PeanutButterSandwich> to a List<Comparable<?>>, but not to a List<Comparable<Object>>.
The way to resolve the problem depends on what you want to do with the list. I suspect you want to extract a Comparable from the list and compare it to an arbitrary Object. If that's what you want, then you need to change the method that receives the list so that its signature only accepts a List<Comparable<Object>> and presumably modify whatever other code produced that list in the first place so that it has the right type available.
If the caller was really giving you a List<Comparable<PeanutButterSandwich>> you'll have a problem; but it's a fundamental logic bug in your program. Trying to compare a random Object to a PeanutButterSandwich which is a plain old bug, and the fact that generics are being difficult here is a symptom of them doing their job correctly.
There is a simpler way (you did not define nice):
List<Comparable<?>> to List<Comparable<Object>>:
(List<Comparable<Object>>)((List)list)
PS: I TESTED IT.
(edit by MightyPork ↓)
Here's a sample code proving that it works:
List<Comparable<?>> list = new ArrayList<Comparable<?>>();
// due to auto-boxing, those will turn into String, Integer and Boolean,
// all implementing Comparable
list.add("dfg");
list.add(1);
list.add(true);
List<Comparable<Object>> foo = (List<Comparable<Object>>)((List)list);
System.out.println(foo.get(0)); // this works
Because of the way generics works (type erasure), there really is no safe way to do this. You don't have any guarantees at runtime on what ? really is.
What you can try is quantifying the ? type. For example, you can try changing the type to List<Comparable<? extends Object>> instead.
I understand there is some backward compatibility issue, and it is not allowed by compiler.
Method has the same erasure as another method in type
how do others achieve this? Is there any other solution than to define them with different function names?
this is because at bytecodelevel, the generic is removed and you have basically a list of objects.. resulting in two identical method-signatures.
but you could use Integer[] and Double[] instead if it fits your requirements because these ARE different types.
you can make them generic like List and at the time of instantiation just tell what you want to do. Either declare as List or as List.
make a generic list like:-
List<> list= new ArrayList<>();
you can write any parameter like T,V,B or any other in the brackets and then later on on in the main you define the generic parameter either as Integer or as Double. Generally,T is used.
Read generics for better understanding.
Probably you can take the parameter as List of Object. In the implemention, check the class type of the object passed and have a switch to process different for integer and double
Please accept/vote up, if this resolves your query
Specifically, with a SortedMap<Vector<String>, int> I get "dimensions expected after this (int) token." Help!
No, this is not possible. Use Integer instead. Autoboxing takes care of the rest (i.e. for most purposes you can program as if you had actually used int because Java converts to and from Integer automatically for you).
Konrad is correct. Alternately, you can use the trove class TObjectIntHashMap to map Objects to primitive ints.