How to create an LinkedList<Object[]>[]? - java

What would be the syntax to create a LinkedList<Object[]>[] type variable?
I have tried:
public LinkedList<Object[]>[] myList = new LinkedList<Object[]>()[];
but this doesn't work.

In Java you can't create generic arrays. You can however do this with ArrayList class or any class that implements the List interface.
List<LinkedList<Object[]>> myList = new ArrayList<LinkedList<Object[]>>();

The declaration LinkedList<Object[]>[] means an array of lists of arrays - is that the intention?
Assuming that it is, you create it with the syntax for creating arrays:
public LinkedList<Object[]>[] myArray = new LinkedList[ARRAY_SIZE];
This creates an array of the specified size (ARRAY_SIZE), each cell of which is null.
Note that:
Since you can't create generic arrays in Java, as Hunter McMillen noticed, the right part omits the type of the LinkedList (i.e. "<Object[]>").
I took the liberty of renaming the variable from myList to myArray, since it's an array and not a list.
It's usually a good idea to use the interface (List) and not a specific implementation (LinkedList), unless you need to use methods specific to LinkedList.
So the line would look like this:
public List<Object[]>[] myArray = new List[ARRAY_SIZE];

Related

Arrays.asList("") returns List interface, how can object creation be possible in this case? [duplicate]

This question already has answers here:
How can Arrays.asList return an instantiated List?
(3 answers)
Closed 7 years ago.
I know that an object cannot be created from an interface like this :
List list2 = new List(); // error.
When i work with Arrays.asList(),i'm confused, because this function returns List and the following code works perfectly:
List list1 = Arrays.asList("a","b","c"); // works perfectly
Right side of this equation returns List. Then the code becomes List list1=new List(); How can this be possible and how this code works although the right side returns an interface, i didn't understand. Can you explain it please?
Thanks in advance
Arrays.asList(...) returns a new ArrayList.
Due to polymorphism it can state that it returns a List, and then return anything that implements the List interface. An ArrayList is a list, so it can be returned.
Extra Note: The ArrayList that asList is using is actually created in the Arrays class as an anonymous class that extends the functionality of the ArrayList class to create a constructor that accepts a native array.
List is an "Interface". You cannot create a new instance ( via new ...) from an Interface, you need a "real" class for that. Arrays.asList is a method that returns an object.
For your first code, you must do something like...
List list2 = new ArrayList();
ArrayList is a Class that implements the List interface. But sorry, I fear that you need to consult some basic Java and OOP tutorials to understand what classes, interfaces, objects, etc. really are, as this is not the place for something like this.
The thing is that List is an interface, not a class. You can only instantiate classes, not interfaces under Java. So you either need to create a new type that implements List (e.g. ArrayList or LinkedList, i.e. List list2 = new ArrayList();) or you can obtain a list like you did by calling a method that creates a list.

Is it necessary to use generics with ArrayList?

It is necessary to use generics with ArrayList? Like this:
ArrayList<Object> software=new ArrayList<Object>();
Can I write it without it? Because I face a problem when I want to add object to it.
What I try to do is to get info from the frame and then create object and add it to tha arraylist
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList software= new ArrayList();
String s = (String) major.getSelectedItem();
if((e.getActionCommand()).equals("SAVE")){
int st_id=Integer.parseInt(id.getText());
String st_name=name.getText();
String st_gender = (String) gender.getSelectedItem();
String st_major = (String) major.getSelectedItem();
String code1=code_sw1.getText();
String code2=code_sw2.getText();
String code3=code_sw3.getText();
double mark1=Double.parseDouble(m_sw1.getText());
double mark2=Double.parseDouble(m_sw2.getText());
double mark3=Double.parseDouble(m_sw3.getText());
St_Sw ob1=new St_Sw(st_id,st_name,st_gender,st_major,code1,code2,code3,mark1,mark2,mark3);
software.add(ob1);
}
}
}
What you mean is not parameter, it's a generic type. You can do a raw list like this:
List list = new ArrayList();
and it will work fine however the whole point of introducing generics in Java was to "fix" raw lists. If you store different objects than Object then it might go wrong when you for example iterate through the list and call one method on each element.
It technically isn't necessary, and you can make an ArrayList without a type and have everything work just fine.
That being said, you should consider it necessary and whenever you run into a situation where you have to not type it, you are probably doing something wrong. Chances are you should look into polymorphism/inheritance (http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29), or interfaces (http://docs.oracle.com/javase/tutorial/java/concepts/interface.html) so that you can store multiple types of objects in the same ArrayList.
The main reason you want to type all of your ArrayList is so that Java will tell you when you try to so something wrong. At first, you might think that this is causing the problem, and making it stop yelling at you is always better than it not compiling. In reality, though, if Java is yelling at you, you are doing something wrong.
In your case, it appears that the arrayList only contains St_Sw Objects. If that is the case, you would want to make your ArrayList with:
ArrayList<St_Sw> software=new ArrayList<St_Sw>();
Since Java 7 you can use the diamond operator:
ArrayList<Object> software=new ArrayList<>();
Arraylist is a dynamic array with means that new memory is allocated when you add new items to the list. There is no need to define the size before creating a arraylist. To add a object just call the add method for software.
As mentioned before,
List list = new ArrayList();
but also:
List<String> list = new ArrayList();
Is valid code in Java, and is supported for backwards compartibility reasons, as Java started having raw, non-generic types for structures like List etc. Non-generic types do not provide safety of type checking in compile time and should be avoided in new code, in general (Look here for more).
However, you can use diamond type inference for a shorthand, putting an "empty" diamond on the right side.
In Java, this
List<String> list = new ArrayList<>();
Is equal to this
List<String> a = new ArrayList<String>();

How can Arrays.asList return an instantiated List?

Arrays.asList returns a typed List. But List is an interface so how can it be instantiated? If try and instantiated a typed List I get an error saying it is not possible.
Edit
Nevermind I see what's going on, just got confused by the docs for a moment.
It's an Arrays.ArrayList which shouldn't be confused with java.util.ArrayList. It is a wrapper for the array which means any changes you make, alter the original array, and you can't add or remove entries. Often it is used in combination with ArrayList like
List<String> words = new ArrayList<>(Arrays.asList("Hello", "There", "World"));
A List can't be instantiated, sure. But you can instantiate a class which implements List -- for example, an ArrayList or LinkedList, etc. These classes really are Lists. The point of returning a List (the interface type) is that the method can return any object which implements the List interface, and you shouldn't worry about exactly which concrete type it is.
from class Arrays
public static transient List asList(Object aobj[])
{
return new ArrayList(aobj);
}
so when you execute Arrays.asList(...) you will take ArrayList which implements List. nobody will know that, except this one itself.
1 example
String[] array = new String[] {"one","two","three"};
List list = Arrays.asList(array);

Compilation error: Generic array creation

I would like to create an array of ArrayList<String>. I tried the following:
static ArrayList<String>[] displayBlocks = new ArrayList<String>[3];
However, I'm getting a compile time error:
generic array creation
I have added import java.util.*;. How can I get it to compile?
if you want an array of arraylist:
import java.util.ArrayList;
import java.util.List;
public class Foo{
List [] arrayOfLists = new ArrayList[10];
}
Here is a related post. you cant create a generic array of arraylist.
You can do this:
import java.util.ArrayList;
import java.util.List;
public class Foo{
ArrayList<ArrayList<String>> ll = new ArrayList<ArrayList<String>>();
}
This construct is indeed not allowed in Java. You could use the varargs hack:
static List<String>[] displayBlocks = createArray(3);
with
public static <E> E[] createArray(int length, E... elements) {
return Arrays.copyOf(elements, length);
}
Needless to say, a List<List<String>> is better, unless you're extremely tight on memory, but then I'd wonder why you don't use a String[][].
A side from the other answer one can also create the list like this, which might feel a little bit more familiar
static ArrayList<String>[] displayBlocks = (ArrayList<String>[]) new ArrayList[3];
From the Java Language Specification section on array creation expressions:
It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (ยง4.7). . . . The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.
Like others have said, use an ArrayList of ArrayLists, or else use a cast (where you might want to also suppress unchecked conversion warnings).
What you are doing wrong :
You have not created an object. Remember that in java
1) All objects have constructors.
2) Constructors are methods.
3) To create an object, you must call the constructor , thus, you are calling a method !
Your desire is ambiguous . But it will be good to read both of these answers :
1) You could make an Array of array lists : This is a data structure with 10 array lists. it is essentially a 2D array where the amount of columns per row is variable, but there will only be 10 rows.
This would be an odd data structure to create. It might represent, for example, a domain model where you have exactly 10 people and each of those people had a variable number of dvds in their dvd collection. so you would have 10 rows, each one with an array list in it.
static ArrayList[] displayBlocks = new ArrayList[10];
not that there is no () here, just a [] * This is because we havent populated our array, rather, we just declare that there is an array with 10 slots, and each slot will have type "ArrayList". To populate, you would have to iterate and add displayBlock[0]=new ArrayList(), for 0-9.
2) Probably, you just wanted a simple array list , which is a linear collection of items.
To do this you would simply declare :
Collection a = new ArrayList();
//or
List a = new ArrayList();
Now ... you should ask yourself why you can declare the variable as either a Collection or a List, if you want to really java's collections work.

ArrayList initialization equivalent to array initialization [duplicate]

This question already has answers here:
Create ArrayList from array
(42 answers)
Initialization of an ArrayList in one line
(34 answers)
Closed 6 years ago.
I am aware that you can initialize an array during instantiation as follows:
String[] names = new String[] {"Ryan", "Julie", "Bob"};
Is there a way to do the same thing with an ArrayList? Or must I add the contents individually with array.add()?
Arrays.asList can help here:
new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
Yes.
new ArrayList<String>(){{
add("A");
add("B");
}}
What this is actually doing is creating a class derived from ArrayList<String> (the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.
I understand that Java 7 will provide additional language constructs to do precisely what you want.
EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)
Here is the closest you can get:
ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));
You can go even simpler with:
List<String> list = Arrays.asList("Ryan", "Julie", "Bob")
Looking at the source for Arrays.asList, it constructs an ArrayList, but by default is cast to List. So you could do this (but not reliably for new JDKs):
ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")
Arrays.asList("Ryan", "Julie", "Bob");
Well, in Java there's no literal syntax for lists, so you have to do .add().
If you have a lot of elements, it's a bit verbose, but you could either:
use Groovy or something like that
use Arrays.asList(array)
2 would look something like:
String[] elements = new String[] {"Ryan", "Julie", "Bob"};
List list = new ArrayList(Arrays.asList(elements));
This results in some unnecessary object creation though.
The selected answer is: ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
However, its important to understand the selected answer internally copies the elements several times before creating the final array, and that there is a way to reduce some of that redundancy.
Lets start by understanding what is going on:
First, the elements are copied into the Arrays.ArrayList<T> created by the static factory Arrays.asList(T...).
This does not the produce the same class as java.lang.ArrayListdespite having the same simple class name. It does not implement methods like remove(int) despite having a List interface. If you call those methods it will throw an UnspportedMethodException. But if all you need is a fixed-sized list, you can stop here.
Next the Arrays.ArrayList<T> constructed in #1 gets passed to the constructor ArrayList<>(Collection<T>) where the collection.toArray() method is called to clone it.
public ArrayList(Collection<? extends E> collection) {
......
Object[] a = collection.toArray();
}
Next the constructor decides whether to adopt the cloned array, or copy it again to remove the subclass type. Since Arrays.asList(T...) internally uses an array of type T, the very same one we passed as the parameter, the constructor always rejects using the clone unless T is a pure Object. (E.g. String, Integer, etc all get copied again, because they extend Object).
if (a.getClass() != Object[].class) {
//Arrays.asList(T...) is always true here
//when T subclasses object
Object[] newArray = new Object[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
a = newArray;
}
array = a;
size = a.length;
Thus, our data was copied 3x just to explicitly initialize the ArrayList. We could get it down to 2x if we force Arrays.AsList(T...) to construct an Object[] array, so that ArrayList can later adopt it, which can be done as follows:
(List<Integer>)(List<?>) new ArrayList<>(Arrays.asList((Object) 1, 2 ,3, 4, 5));
Or maybe just adding the elements after creation might still be the most efficient.
How about this one.
ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");
This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-
List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();
It's a very cool library that saves you a tonne of time.

Categories

Resources