Created
January 25, 2017 11:26
-
-
Save akaliacius/18152f97796f6b2e923695b185eebb55 to your computer and use it in GitHub Desktop.
how can we use java array with generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class GenericArray <T>{ | |
private ArrayList<T> arrayList; | |
private Object[] array; | |
// constructor with parameter ArrayList | |
public GenericArray(ArrayList<T> list){ | |
arrayList = list; | |
array = null; | |
} | |
// constructor with parameter array | |
public GenericArray(Object[] array){ | |
arrayList = null; | |
this.array = array; | |
} | |
// method to print all items inside ArrayList | |
public void printArrayList(){ | |
for(T item : arrayList){ | |
System.out.println(item.toString()); | |
} | |
} | |
// method to print all items inside array | |
public void printArray(){ | |
for(Object obj : array){ | |
// we need this ugly casting here and all done | |
T item = (T) obj; | |
System.out.println(item.toString()); | |
} | |
} | |
// let's make all this stuff running | |
public static void main(String[] args){ | |
// first ArrayList | |
ArrayList<String> list = new ArrayList<>(); | |
list.add("Hello"); | |
list.add("world"); | |
list.add("from"); | |
list.add("ArrayList"); | |
GenericArray<String> arrayList = new GenericArray<>(list); | |
arrayList.printArrayList(); | |
System.out.println(); | |
// now array | |
String[] arr = {"Hello", "world", "from", "array"}; | |
GenericArray<String> array = new GenericArray<>(arr); | |
array.printArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment