While defining a 2D dynamic array why can't I define it like this:
List<List<Integer>> t=new List<List<Integer>();
On doing so, I got an error saying:
Cannot instantiate the type List<List<Integer>>
I came to know that this is the best practice for it-
List<List<Integer>> t=new Arraylist<List<Integer>>();
why is it so.can someone help me understand this.
List is an interface an as such can not use new to create a new instance of it, you need classes that implement it instead eg ArrayList
List<List<Integer>> t=new ArrayList<List<Integer>>();
or since java 7
List<List<Integer>> t = new ArrayList<>();
Because in Java, List is an Interface you can't initialize it.
You can do it like that;
List<t> list = new ArrayList<t>();
Just initialize any types that implement the List Interface
Related
I have a function that returns a list of lists of integers
public List<List<Integer>> threeSum(int[] nums)
Obviously I can't directly instantiate a List so I chose to use an ArrayList and tried to instantiate my return value as such:
List<List<Integer>> ans = new ArrayList<ArrayList<Integer>>();
The above did not work but this did:
List<List<Integer>> ans = new ArrayList<List<Integer>>();
My understanding is that List is an interface that ArrayList inherits from. Why, then, can I instantiate an ArrayList of Lists and be ok but I can't instantiate an ArrayList of ArrayLists?
For readability the first few lines of my function look as such:
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (nums.length < 3) return ans;
This is because an ArrayList<ArrayList<Integer>> is NOT a List<List<Integer>>.
The reason is that a List<List<Integer>> is something that you should be able to add a LinkedList<Integer> to. But you can't add a LinkedList<Integer> to an ArrayList<ArrayList<Integer>> because it's the wrong type.
Therefore, if you've got an ArrayList<ArrayList<Integer>>, you can never treat it as a List<List<Integer>>, or reference it with a variable of type List<List<Integer>>
but I can't instantiate an ArrayList of ArrayLists?
because you specified type of ans as List of Lists not List of ArrayLists.
List<List<Integer>> ans = new ArrayList<ArrayList<Integer>>();
The above did not work
I guess it will work if declaration will be:
List<? extends List<Integer>> ans = new ArrayList<ArrayList<Integer>>();
This is Java Generics. List<List<Integer>> ans = new ArrayList<ArrayList<Integer>>() does not work because the outer list expects itself to keep List<Integer>, not ArrayList<Integer>.
Consider this:
List<Number> list = new ArrayList<Integer>();
This does not work either, because the list expects Number, not Integer.
Anyway when nesting lists, you need to instantiate inner lists as well. Lists of Lists do not work like multidimensional arrays.
One of the questions I have been given asks:
All the lines should be stored in an object of
type List<Set<Integer>>.
How do you write this in Java, as in how do you initialise this list? I've never seen this before.
Please provide a link to an explanation as i'm not sure what this is called in Java so have no idea about how to learn about it. Thank You.
Its a List of Sets where each Set can hold only Integers.
Set<Integer> singlesSet = new HashSet<>();
singlesSet.add(1);
singlesSet.add(2);
Set<Integer> tensSet = new HashSet<>();
tensSet.add(10);
tensSet.add(20);
List<Set<Integer>> list = new ArrayList<>();
list.add(singlesSet);
list.add(tensSet);
System.out.println(list);
Example of usages of Set and List. Note that elements in a TreeSet are always sorted.
List<Set<Integer>> listofsets = new ArrayList<Set<Integer>>();
Set<Integer> set1 = new TreeSet<Integer>();
set1.add(1);
set1.add(2);
Set<Integer> set2 = new TreeSet<Integer>();
set2.add(6);
set2.add(4);
listofsets.add(set);
// listofsets = {{1,2}, {4,6}}
Like this List<Set<Integer>> yourList = new ArrayList<Set<Integer>>();?
You may want to take a look at https://docs.oracle.com/javase/7/docs/api/java/util/List.html
The short way:
List<Set<Integer>> list = new ArrayList<Set<Integer>>();
Set<Integer> set = new HashSet<Integer>();
list.add(set);
set.add(1);
set.add(2);
....
What is the difference between Set and List?
In Java, the List interface represents an abstract list of things. Any class the implements List (for example, LinkedList) must implement its methods and behave according to its contract.
You can essentially think of it as an array, but keep in mind that arrays are only one kind of list, and that implementations of List do no have to use arrays internally.
The Set also represents a collection of elements, but with no relationship or connection between them. Visually, you can think of a set as a sort of bag of things. You can add and remove things from the bag, but none of the items need to be related.
An Integer, of course, is just an object wrapper around Java's int primitive.
As such, a List<Set<Integer>> object would be similar to a two-dimensional array, only without a defined order in the second dimension.
You would initialize a List<Set<Integer>> as follows:
List<Set<Integer>> myList = new ArrayList<HashSet<Integer>>();
Where ArrayList and HashSet can be any classes that implement List and Set, respectively.
I encountered a problem while solving problems on LeetCode. The question has a form:
public List<List<Integer>> generate(){
}
that requires returning a List<List<Integer>>. I know for List<T> I can do a LinkedList<T> or ArrayList<T>. How can I instantiate it that the compiler would not complain? Thanks
return new ArrayList<List<Integer>>();
The outer list type needs to be a concrete type like ArrayList or LinkedList, but the inner list type should be List. On more recent Java versions, you can do
return new ArrayList<>();
List<List<Integer>> myList = new ArrayList<List<Integer>>();
Then when you want to add stuff to it do
List<Integer> innerList = new ArrayList<Integer>(); myList.add(innerList);
Assuming that I have a class named Class,
And I would like to make a new ArrayList that it's values will be of type Class.
My question is that: How do I do that?
I can't understand from Java Api.
I tried this:
ArrayList<Class> myArray= new ArrayList ArrayList<Class>;
You are looking for Java generics
List<MyClass> list = new ArrayList<MyClass>();
Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html
If you just want a list:
ArrayList<Class> myList = new ArrayList<Class>();
If you want an arraylist of a certain length (in this case size 10):
List<Class> myList = new ArrayList<Class>(10);
If you want to program against the interfaces (better for abstractions reasons):
List<Class> myList = new ArrayList<Class>();
Programming against interfaces is considered better because it's more abstract.
You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.
You're very close. Use same type on both sides, and include ().
ArrayList<Class> myArray = new ArrayList<Class>();
You can use in Java 8
List<Class> myArray= new ArrayList<>();
Fixed the code for you:
ArrayList<Class> myArray= new ArrayList<Class>();
Do this: List<Class> myArray= new ArrayList<Class>();
Java 8
In order to create a non-empty list of fixed size where different operations like add, remove, etc won't be supported:
List<Integer> fixesSizeList= Arrays.asList(1, 2);
Non-empty mutable list:
List<Integer> mutableList = new ArrayList<>(Arrays.asList(3, 4));
Java 9
With Java 9 you can use the List.of(...) static factory method:
List<Integer> immutableList = List.of(1, 2);
List<Integer> mutableList = new ArrayList<>(List.of(3, 4));
Java 10
With Java 10 you can use the Local Variable Type Inference:
var list1 = List.of(1, 2);
var list2 = new ArrayList<>(List.of(3, 4));
var list3 = new ArrayList<String>();
Check out more ArrayList examples here.
ArrayList<Class> myArray = new ArrayList<Class>();
Here ArrayList of the particular Class will be made. In general one can have any datatype like int,char,
string or even an array in place of Class.
These are added to the array list using
myArray.add();
And the values are retrieved using
myArray.get();
Material please go through this Link
And also try this
ArrayList<Class> myArray= new ArrayList<Class>();
I have an ArrayList<String> that I'd like to return a copy of. ArrayList has a clone method which has the following signature:
public Object clone()
After I call this method, how do I cast the returned Object back to ArrayList<String>?
Why would you want to clone? Creating a new list usually makes more sense.
List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);
Job done.
ArrayList newArrayList = (ArrayList) oldArrayList.clone();
This is the code I use for that:
ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);
Hope is usefull for you
With Java 8 it can be cloned with a stream.
import static java.util.stream.Collectors.toList;
...
List<AnObject> clone = myList.stream().collect(toList());
Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.
I think this should do the trick using the Collections API:
Note: the copy method runs in linear time.
//assume oldList exists and has data in it.
List<String> newList = new ArrayList<String>();
Collections.copy(newList, oldList);
I find using addAll works fine.
ArrayList<String> copy = new ArrayList<String>();
copy.addAll(original);
parentheses are used rather than the generics syntax
List<String> shallowClonedList = new ArrayList<>(listOfStrings);
Keep in mind that this is only a shallow not a deep copy, ie. you get a new list, but the entries are the same. This is no problem for simply strings. Get's more tricky when the list entries are objects themself.
If you want this in order to be able to return the List in a getter it would be better to do:
ImmutableList.copyOf(list);
To clone a generic interface like java.util.List you will just need to cast it. here you are an example:
List list = new ArrayList();
List list2 = ((List) ( (ArrayList) list).clone());
It is a bit tricky, but it works, if you are limited to return a List interface, so anyone after you can implement your list whenever he wants.
I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with List -the generic parent- not ArrayList
Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.
This should also work:
ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()
ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();
I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).
public static <T extends Object> List<T> clone(List<T> list) {
try {
List<T> c = list.getClass().newInstance();
for(T t: list) {
T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
c.add(copy);
}
return c;
} catch(Exception e) {
throw new RuntimeException("List cloning unsupported",e);
}
}