How to assign accepted objects to generics? - java

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.

Related

java colletion and arraylist

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.

How are List and List<String> different?

I'd just started working with lists and wanted to know how both of these are different?
Im guessing the second one specifically points out that it contains only string type stuff, while the first one is more flexible.
But then if the first is more flexible, why do people use the second one ever?
It's called generics.
The second one specifies this is a list of Strings and will throw a compiler error if you try to put something else.
It is useful to prevent people from putting anything besides a String in the List.
Here is a link to the java generic tutorial.
List<E> : Its generic and E will be any object i.e it will contain List of Object.
List<String> : The data type of list is string i.e it can only contain String.
It depend on the requirement what is the need of datatype of List.May be whatever example you looked require list of String.

How to write a overloaded function which can accept List<Integer> or List<Double> in java?

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

Returning two different values from method

I have method that parses a list of String records into objects and returns List of objects. So my method signature is like this.
public List<ParsedObject> parse(String[] records);
But I also want to return, other metrics like number of string records that were not parsed successfully. Now I get confused, how to return this metric. One option would be to create another wrapper class that holds both list of parsed records and members to store these metrics.
But I face this situation very often and this way I would end up in creating many wrapper classes.
Not sure if I explained well. Any suggestions here?
Java does not support returning multiple values from a function, unfortunately. You can create a wrapper class, like you said. Another option is to pass in an array of integers or a "metrics" object or something like that and modify it inside Parse. Slightly better might be to have one or more instance variables (rather than method variables) to keep track of any sort of diagnostic information you need.
Your question has already been discussed (see this for example: Should Java method arguments be used to return multiple values? ). I personally think that you should either make two method calls, if the returned data is not related. If they are, then you should create a "wrapper" class as you call it. If they really are related data then they probably belong in the same class anyway.
I don't personally favor modifying passed in objects because to me it is a side effect, and it is not clear to see what the method really does.
Another way to think of it is to use the factory pattern (see http://en.wikipedia.org/wiki/Factory_method_pattern) if the object you are building is complex.
Create a ParseResult object. You could include the List, number of records parsed, errors, etc. Make it generic enough so that it could be returned from different methods. You could even make it a base class and return classes that extend from it. Just keeping thinking in terms of objects.
You can return a complex object containing the list and all the information you need.
Maybe this could help http://www.yoda.arachsys.com/java/parameters.html
I was going to suggest to you some kind of 'c++ pair' type, but then I found this: What is the equivalent of the C++ Pair<L,R> in Java?
A wrapper class is the standard way of returning more information from a function. Another alternative would be to pass another parameter by reference and modify it in your function, thus effectively returning new information to the caller. For example, in your case you would pass an empty list and add all the parsed elements in that list. The return type could be a metric or an error code. Thus the caller will have both pieces of information.
This is a very common problem for many people who develop using Java. In other languages, such as Scala, one can create tuples, which are anonymous objects which can hold multiple values, and use them as arguments or return values.

Stacking generics

Is this bad practice?
ArrayList<ArrayList<ArrayList<Double>>> list = new ArrayList<ArrayList<ArrayList<Double>>>();
It is a three-dimensional matrix based on ArrayList. Doesn't look nice, but that's how we have to write it.
An alternative could be:
List<List<List<Double>>> list = new ArrayList<List<List<Double>>>();
which is a bit shorter and usually OK as in most cases your just interested in the interface methods.
So if you need a resizable threedimensional matrix data structure, then this is a clean approach.
This is not necessarily bad practice. It's just "unreadable". Have a bit of patience, in the upcoming Java 7 you're allowed to omit the cruft in specific generic types when constructing the parameterized type:
List<List<List<Double>>> list = new ArrayList<>();
This is called type inference.
As of now, if you can live with compiler warnings, you can also just do so:
List<List<List<Double>>> list = new ArrayList();
It would probably be a good idea to create a new class to handle the behavior you are trying to accomplish. I would create a class that uses an private ArrayList<...> (favor delegation over inheritance) and create necessary methods. If anything it should make things easier to read and understand.
yes. most likely your code is better off with double[][][]
Well, do you need to have a List whose elements are Lists whose elements are Lists? We have no idea what it is you are trying to accomplish unless you tell us.
However, using ArrayList directly rather than List is indeed a bad practice.
Depends on how you intend to use this. Perhaps you could encapsulate the two dimensional list and end up with a List<TwoDimensionalList<Double>>. Presumably it would have operations such as TwoDimensionalList.get(int i, int j) to get an element in the jth position of the ith list.
edit: if it's not a list of two dimensional lists, but rather a three dimensional list, then of course you want a ThreeDimensionalList. (and if your list's dimensions are fixed, you could implement this internally with a single array(list) where element (i,j,k) is located at position i*dim1 + j*dim2 + k*dim3).
At the least, naming it more expressively, something like 3dList, would help.
Preferred, for me, is to write a custom encapsulation of 2D/3D list, as others have suggested above.

Categories

Resources