creating lists in java - java

So I am pretty new to java, and am trying to create a list in java with this:
private creatureKind[] field = new creatureKind[7];
creatureKind being another class I created within the same package. Is this the right syntax? I am trying to call functions such as set(), which
I found on this link: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#set-int-E-, but I am getting an error message that abridged is saying that field is an array type. Not a frequent poster of this site so sorry if I messed stuff up in advance.

What you defined is a static array with a 7 element.
If you want to define a list, or better, an ArrayList you should it as follows:
List<creatureKind> list = new ArrayList<>();
Note that this is an unbound list, you should add values, before setting values. In general, I would suggest reading the documentations: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

If I understood your question correctly, you might need to do the following:
List<creatureKind> myList = new ArrayList<>();

Related

Create an ArrayList with type of an object array

Like the title says, I am trying to instantiate an ArrayList with type of a class that I want to be an array. Probably I did not explain it correctly in technical terms, so let's just look at a pseudo code:
List<TestClass[5]> lTestList = new ArrayList<TestClass[5]>();
Where should I specify the size of the TestClass type array?
Apologies if my explanation does not make much sense as I am still learning.
The type of a TestClass array is TestClass[]. So you need to use that as your generic parameter.
List<TestClass[]> lTestList = new ArrayList<TestClass[]>();
Then when you add items to your list, you can add arrays of the appropriate size.
lTestList.add(new TestClass[5]);
List<TestClass[]> lTestList = new ArrayList<TestClass[]>();
You shouldn't specify size of array in generic.

What kind of List is List<Object> list = Database.getAllData();?

I have the following question:
if I have the following line of code:
List<Position> allPos = posDBM.getAllPos();
Position is an object
posDBM is a SQLite Database Manager class, which manages the SQLite database,
getAllPos() returns all database data.
The return type of getAllPos() is List<Position>.
If I want to initialize a List<> like this List<Position> pos = new, I have to specify the type of the List (ArrayList, LinkedList, etc.) .
So back to my question, what kind of List do I have, after I filled the list from the database?
I would guess it's an ArrayList , but I can't find any source to back this up. It's just a matter of interest...
You don't have to know; that's the point. The interface is what matters to you, not the implementation.
You can't know without looking at the source of that method. But even if you do, it's immaterial to your client. All you call are List methods.
That you will find in getAllPos() source code. List<Position> due to Polymorphism will accept all classes implementing List interface.
It you are just curious, then one way to find out is to do something like this:
List<Position> allPos = posDBM.getAllPos();
System.out.println("The class is " + allPos.getClass().getName());
Of course, you don't need to know ... because you don't need to instantiate the list implementation class yourself. The database management code deals with that.
The returned List<Position> is a generic or a Strongly Typed list. The option that you were asking is about ArrayList which specifies a list that can take up any object. This will require an overhead of Boxing and Unboxing when writing / reading using the ArrayList.
Ideally you should not worried about the actual implementation , once you have List returned from the method call , you can just iterate over it like this .
List<Position> allPos = posDBM.getAllPos();
for(Position position : allPos){
//Your code goes here
}
And if you want to initialize a new list you can do it in many ways by using different implementations of List interface , now which implementation you want to choose very much depends on your requirement.
I would suggest you to add a breakpoint and see allPos variable after posDBM.getAllPos(), the debugger should tell you the Type.

Having trouble understanding how to create an array of linkedlists

Ok, so I have been reading every google result about creating an array of linkedlist, and most of the stack overflow threads, but I don't really understand what they are doing. Do I need to create a seperate class that extends linkedlist and then create an array of that class?
I have tried a million different ways of arranging this code, but this is what I have at the moment.
public static int[][] genPerms(int numElements, int totPerms) {
int permArray[][] = new int[totPerms][numElements];
LinkedList<Integer>[] elementsLeftList = new LinkedList<Integer>[numElements];
The error is generic array creation. Can someone explain to me what is actually going on here.
In addition to the solutions below I was told you can create an array of head pointers.
Thanks in advance.
It's not allowed to create generic arrays, do the following
#SuppressWarnings("unchecked")
LinkedList<Integer>[] elementsLeftList = new LinkedList[numElements];
it works OK
You can't currently create an array of generics in Java without going through a complicated process. Can you do the following instead?
List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();
If you really need it as an array you can then get it from elementsLeftList.toArray() and cast the result.
You can read the following link for the explanation: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104

Java: How to initialize a List of Typed Objects?

So I've been searching a while for the answer to this and I'm just not sure how it works.
I'm trying to make a list of BloomFilter<String> objects.
The class definition for the BloomFilter is:
public class BloomFilter<E> implements Serializable { ...
The <E> allows the user to pick what type of elements are going into the filter. In my case, I need strings.
Somewhere else in the program, I need 4 BloomFilter<String> objects.
My question is: How do I initialize the following line?
private static BloomFilter<String> threadedEncrpytionFilters[] = null;
threadedEncryptionFilters = ???
This seems similar to creating a list of ArrayLists? Is that also possible?
After seeing that someone alread answered this question I wanted to remove this answer but I see by the comments that people are still confused so here it goes :)
The specification clearly states, that what you want to do is illegal. Meaning:
BloomFilter<String> threadedEncrpytionFilters[] = new BloomFilter<String>[4];
won't compile. You can't create an array of concrete generic classes. When it comes to generics you can store in arrays only:
raw types
unbounded wildcard parameteriezd types
The workaround to your problem is, as already stated, to change the array to a List<BloomFiler<String>>.
This behaviour is actually pretty logical if you take into account how Java handles generic types at different stages (compile, runtime etc). After understanding that you'll see that arrays of concrete generic types wouldn't be type-safe. Here's a mighty good read on this subject: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104
List<BloomFilter<String>> list = new ArrayList<BloomFilter<String>>();
list.add(new BloomFilter<String>());
list.add(new BloomFilter<String>());
list.add(new BloomFilter<String>());
// ... and so on
Consider this:
private static List<BloomFilter<String>> threadedEncrpytionFilters =
new ArrayList<BloomFilter<String>>();

How to create a new list of same type as old list in Java?

I'm trying to write a method that takes in a List and create a new List of the same type based on it. That is, if the input list is an ArrayList, then I want the method to create a new ArrayList. The problem is that the program won't know if the List is an ArrayList or a LinkedList until runtime.
So far I've tried using the clone() method, but I don't think it works because the List class doesn't have clone() defined, and when I cast the input list as an Object and then clone then recast as a List, it also doesn't work (I'm not sure why).
All the standard lists from the JDK support clone, so
List copy = (List)((Cloneable)somelist).clone()
should work fine.
of course you can use reflection
Class c = somelist.getClass();
List newlist = (List)c.newInstance();
newlist.addAll(somelist);
Can you say more about why you want to do this? Without a good rationale, I'd contend:
Consider not doing this at all, but instead:
static <T> List<T> cloneMyList(final List<T> source)
{
return new ArrayList<T>(source);
}
If what you REALLY want is an efficient way to create a second copy of a known list, maybe the underlying implementation type really doesn't matter. In that case, just use an ArrayList which can be efficiently allocated using the List copy constructor.
Here it is:
List<YourType> destinationList = new ArrayList<>(sourceList.size());
Collections.copy(destinationList, sourceList);

Categories