How to add multiple object in ArrayList which declared generic? - java

How to do that?
Following is tried code.
[Tried code]
package com.company;
import java.util.ArrayList;
import java.util.Date;
public class Main {
public static void main(String[] args) {
ArrayList<String, Integer, Date> myArray = new ArrayList<String, Integer, Date>();
myArray.add("FIRST");
myArray.add("SECOND");
myArray.add("THIRD");
// add multiple object
myArray.add(new Integer(10));
// add multiple object
myArray.add(new Date());
}
}

Yes, But not recommended.
ArrayList<Object> myArray = new ArrayList<Object>();
Taking Object as a type , it accept all the types.
ArrayList<Object> myArray = new ArrayList<Object>();
myArray.add("FIRST"); //accepted
myArray.add(new Integer(10)); //accepted
myArray.add(new Date()); //accepted
So while getting also you need to take care of which Object you are getting back.
But, good recommendation is to take that individual list's for each type.

The below line wouldn't even compile.
ArrayList<String, Integer, Date> myArray = new ArrayList<String, Integer, Date>();
What you're trying to achieve can be done using
ArrayList<Object> myArray = new ArrayList<>(); // Object type
but it is not at all a recommended option to do it. And while fetching the values back from the ArrayList, you need to handle the different types of objects manually, which is quite troublesome as well.
Therefore, it is always create ArrayList of the specific types you want to use.
ArrayList<String> myString = new ArrayList<>(); // For strings
ArrayList<Date> myDates = new ArrayList<>(); // For Date

Related

Java object array declaration [duplicate]

I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
and then create an array of MyObjectArrayList.
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
There is a easier way to create generic arrays than using List.
First, let
public static ArrayList<myObject>[] a = new ArrayList[2];
Then initialize
for(int i = 0; i < a.length; i++) {
a[i] = new ArrayList<myObject>();
}
You can do
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList<?>[2];
or
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList[2];
(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: #SuppressWarnings("unchecked")
if you are trying to declare an arraylist of your generic class you can try:
public static ArrayList<MyObject> a = new ArrayList<MyObject>();
this will give you an arraylist of myobject (size 10), or if u only need an arraylist of size 2 you can do:
public static ArrayList<MyObject> a = new ArrayList<MyObject>(2);
or you may be trying to make an arraylist of arraylists:
public static ArrayList<ArrayList<MyObject>> a = new ArrayList<ArrayList<MyObject>>();
although im not sure if the last this i said is correct...
It seems to me that you use the wrong type of parenthesis. The reason why you can't define an array of generic is type erasure.
Plus, declaration of you variable "a" is fragile, it should look this way:
List<myObject>[] a;
Do not use a concrete class when you can use an interface.

How to initialize an Array of Sets of HashMaps [duplicate]

I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
and then create an array of MyObjectArrayList.
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
There is a easier way to create generic arrays than using List.
First, let
public static ArrayList<myObject>[] a = new ArrayList[2];
Then initialize
for(int i = 0; i < a.length; i++) {
a[i] = new ArrayList<myObject>();
}
You can do
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList<?>[2];
or
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList[2];
(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: #SuppressWarnings("unchecked")
if you are trying to declare an arraylist of your generic class you can try:
public static ArrayList<MyObject> a = new ArrayList<MyObject>();
this will give you an arraylist of myobject (size 10), or if u only need an arraylist of size 2 you can do:
public static ArrayList<MyObject> a = new ArrayList<MyObject>(2);
or you may be trying to make an arraylist of arraylists:
public static ArrayList<ArrayList<MyObject>> a = new ArrayList<ArrayList<MyObject>>();
although im not sure if the last this i said is correct...
It seems to me that you use the wrong type of parenthesis. The reason why you can't define an array of generic is type erasure.
Plus, declaration of you variable "a" is fragile, it should look this way:
List<myObject>[] a;
Do not use a concrete class when you can use an interface.

How to add generics to my code

I need to use generics for my nestList. What syntax I can use so that both Integer and String lists can be added to nested lists as well as of any other types ?
// integer list
List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));
// string list
List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));
// nested lists.
List nestedList = new ArrayList();
nestedList.add(listInteger);
nestedList.add(listString);
nestedList.add("A");
Since you want to store lists AND non-collection objects ("A") you should store Objects in your collection, like:
import java.util.*;
public class Main {
public static void main(String[] args)
{
// integer list
List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));
// string list
List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));
// nested lists.
List<Object> nestedList = new ArrayList<Object>();
nestedList.add(listInteger);
nestedList.add(listString);
nestedList.add("A");
}
}
Just note that List<Object> is just to avoid the compiler from complaining that your collection doesn't have a type. Effectively, List<Object> and List are the same thing.
You could have suppressed the warning using this:
import java.util.*;
public class Main {
#SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args)
{
// integer list
List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));
// string list
List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));
// nested lists.
List nestedList = new ArrayList();
nestedList.add(listInteger);
nestedList.add(listString);
nestedList.add("A");
}
}
But ultimately, the solution in general is not good.
I don't have all your requirements, but a better idea would be to have an object to store all your collections and objects. You code would be cleaner and free from #SuppressWarnings, which are considered bad.
Something like:
MyObj myobj = new MyObj();
nestedList.setIntegers(listInteger);
nestedList.setStrings(listString);
nestedList.setSomeProperty("A");
Make the type as Object as you are adding different types of Objects(list,String) into the nestedList.
List<Object> nestedList = new ArrayList<Object>();
You can also use type as List only if you are adding list Objects in nestedList.
List<List> nestedList = new ArrayList<List>();
But this will error out if you try to add nestedList.add("A") , also It will also prompt a warning for using raw types.
Making it List<Object> = new ArrayList<>(); would allow you to add any type of Object regardless of type.
Just change this line
List<List> nestedList = new ArrayList<List>();
And it is, because you are storing list in lists, the type is List :)

How to cast ArrayList<> from List<>

Can somebody please explain me why I can't cast List<> to ArrayList<> with first approach and I do with second one? Thank you.
First approach:
ArrayList<Task> tmp = ((ArrayList<Task>)mTrackytAdapter.getAllTasks(token));
Second approach:
ArrayList<Task> tmp = new ArrayList<Task>(mTrackytAdapter.getAllTasks(token));
When you do the second one, you're making a new arraylist, you're not trying to pretend the other list is an arraylist.
I mean, what if the original list is implemented as a linkedlist, or some custom list? You won't know. The second approach is preferred if you really need to make an arraylist from the result. But you can just leave it as a list, that's one of the best advantages of using Interfaces!
When you are using second approach you are initializing arraylist with its predefined values.
Like generally we do
**ArrayList listofStrings = new ArrayList<>();
**
Let's say you have an array with values, now you want to convert this array into arraylist.
you need to first get the list from the array using Arrays utils.
Because the ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.
List<String> listofOptions = (List<String>) Arrays.asList(options);
then you can user constructoru of an arraylist to instantiate with predefined values.
ArrayList<String> arrlistofOptions = new ArrayList<String>(list);
So your second approach is working that you have passed values which will intantiate arraylist with the list elements.
More over
ArrayList that is returned from Arrays.asList is not an actual arraylist, it is just a wrapper which doesnt allows any modification in the list.
If you try to add or remove over Arrays.asList it will give you
UnsupportedOperationException
Try running the following code:
List<String> listOfString = Arrays.asList("Hello", "World");
ArrayList<String> arrayListOfString = new ArrayList(listOfString);
System.out.println(listOfString.getClass());
System.out.println(arrayListOfString.getClass());
You'll get the following result:
class java.util.Arrays$ArrayList
class java.util.ArrayList
So, that means they're 2 different classes that aren't extending each other. java.util.Arrays$ArrayList signifies the private class named ArrayList (inner class of Arrays class) and java.util.ArrayList signifies the public class named ArrayList. Thus, casting from java.util.Arrays$ArrayList to java.util.ArrayList and vice versa are irrelevant/not available.
The second approach is clearly wrong if you want to cast. It instantiate a new ArrayList.
However the first approach should work just fine, if and only if getAllTasks return an ArrayList.
It is really needed for you to have an ArrayList ? isn't the List interface enough ? What you are doing can leads to Runtime Exception if the type isn't correct.
If getAllTasks() return an ArrayList you should change the return type in the class definition and then you won't need a cast and if it's returning something else, you can't cast to ArrayList.
Just try this :
ArrayList<SomeClass> arrayList;
public SomeConstructor(List<SomeClass> listData) {
arrayList.addAll(listData);
}
You can cast List<> to ArrayList<> if you understand what you doing. Java compiler won't block it.
But:
It's bad practice to casting parent type to child type (or interface to implementation type) without checking.
This way better:
if (list instanceof ArrayList<Task>) {
ArrayList<Task> arraylist = (ArrayList<Task>) list;
}
Maybe you don't need implementation type as reference. Look SonarQube warning https://sbforge.org/sonar/rules/show/squid:S1319. You can avoid this casting in the most cases.
You can use Guava method:
ArrayList<Task> arraylist = Lists.newArrayList(list);
The first approach is trying to cast the list but this would work only if the List<> were an ArrayList<>. That is not the case. So you need the second approach, that is building a new ArrayList<> with the elements of the List<>
Because in the first one , you're trying to convert a collection to an ArrayList.
In the 2nd one , you just use the built in constructor of ArrayList
May be:
ArrayList<ServiceModel> services = new ArrayList<>(parking.getServices());
intent.putExtra("servicios",services);
import java.util.List;
import java.util.Arrays;
import java.util.*;
public class Merge
{
public static void main(String[] args) {
// This is normal way
// List<Integer> l1 = new ArrayList<Integer>(); l1.add(2); l1.add(5); l1.add(10); l1.add(22);
// List<Integer> l2 = new ArrayList<Integer>(); l2.add(3); l2.add(8); l2.add(15);
//Array.asList only have the list interface, but ArrayList is inherited from List Interface with few more property like ArrayList.remove()
List<Integer> templ1 = Arrays.asList(2,5,10,22);
List<Integer> templ2 = Arrays.asList(3,8,12);
//So creation of ArrayList with the given list is required, then only ArrayList.remove function works.
List<Integer> l1 = new ArrayList<Integer>(templ1);
List<Integer> l2 = new ArrayList<Integer>(templ2);
List<Integer> l3 = new ArrayList<Integer>();
Iterator itr1 = l1.iterator();
while(itr1.hasNext()){
int x = (Integer) itr1.next();
Iterator itr2 = l2.iterator();
while(itr2.hasNext()) {
int y = (Integer) itr2.next();
if(x < y) {
l3.add(x);
break;
}
else{
l3.add(y);
itr2.remove();
}
}
}
Iterator it = l1.iterator();
while (it.hasNext()){
int k = (Integer) it.next();
if (l3.contains(k)){
continue;
}
else{
l3.add(k);
System.out.println(k);
}
}
Iterator itr2 = l2.iterator();
while (itr2.hasNext()){
int k = (Integer) itr2.next();
l3.add(k);
}
System.out.println(l3);
}
}

How to reclaim the generic type you declared an arraylist to be in Java?

I was just playing around and a thought came to my mind and I decided I want to try it:
Make an ArrayList that holds more ArrayLists.
For example, I created an ArrayList called intList that holds ints, then filled it with values. After that I did a stringList one and filled it too. Then I made an ArrayList that holds other ArrayLists called aList and added intList and stringList to it.
Now the problem I faced was if I was retrieving objects from aList, it would not recognize if the generic type was int or string.
Here is the code I tried:
import java.util.*;
public class Practice {
public static void main(String[] args) {
List<ArrayList> list = new ArrayList<ArrayList>();
ArrayList<int> intList = new ArrayList<int>();
intList.add(1);
intList.add(2);
intList.add(3);
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("One");
stringList.add("Two");
stringList.add("Three");
list.add(intList);
list.add(stringList);
for(ArrayList lst : list) {
for(ArrayList lt : lst) {
System.out.println(lt);
}
}
}
}
Java has "generic type erasure", meaning that the type parameters to generics are "erased". Once you create an ArrayList<T> there's no way to find out what T was.
Only class types can be used as generic type parameters, so you can't have an ArrayList<int>. Use an ArrayList<Integer> instead.
In addition, the types used in your loops are wrong. Since list is a list of lists of values, lst is a list of values, which means that your lt variable will be either an integer or a string, not another ArrayList.
The deeper problem here is that you're still using raw types, so the compiler can't find that error for you. You should declare list as something like List<List<? extends Object>>. That way you can add both an ArrayList<Integer> and an ArrayList<String> to it, and extract the values as type Object within your loop.
Since no type information is stored in generic type, you could get element from sub-list and check it's type:
for(ArrayList subList : list) {
if (subList.size() > 0) {
Class elementClass = subList.get(0).getClass();
// do something else with it
}
}
But:
It will not work, if subList is empty
Generally, the concept of storing several lists of different types in another list looks rather strange.
Type erasure means that at runtime, the type is erased. That's why you can cast from one generic to another:
import java.util.ArrayList;
public class Test {
public static void main(String [] args){
ArrayList<String> list = new ArrayList<String>();
ArrayList list2 = (ArrayList)list;
list2.add(new Integer(5));
System.out.println(list2.get(0).getClass());
}
}
Will output:
class java.lang.Integer
import java.util.*;
public class Practice {
public static void main(String[] args) {
List<ArrayList<?>> list = new ArrayList<ArrayList<?>>();
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("One");
stringList.add("Two");
stringList.add("Three");
list.add(intList);
list.add(stringList);
for(ArrayList<?> lst : list) {
for(Object lt : lst) {
System.out.println(lt);
}
}
}
}

Categories

Resources