Java: How to initialize a fixed length List of List? - java

I have a list of String[] that contains some data returned from a database
List<String[]> x;
Now for each "x" I have to store its relative Ys. (Imagine that "x" contains the elements returned from a "SELECT DISTINCT xColumn1, xColumn2 FROM table" and now for each element I have to store the data from another query).
Y's elements are going to be stored here:
List<List<String[]>> yElements;
I've read that I can declare a fixed length list, but I don't know how. This is what I have done:
yElements = Arrays.asList(new List<String[]>[x.sixe()]);
Netbeans told me "generic array creation" error.
I also want to tell you that I MUST have a fixed lenght list to store a List of String[ ] in a specific index of this List of Lists. (If you can show me how to do with an array it would be great, too!)
Thanks.

If you want your lists to be absolutely fixed size, you could use the native arrays. They can be multi-dimensional so for example you can have String[][] x or `String[][][] y'.
Honestly however, your approach is a bit confusing and not that crisp from a design point of view.
Why not, similarly to as was suggested in the comment, have an object which has both columns (xColumn1, xColumn2), and then have the Y elements in a separate object, which can then be associated with the first one?
so:
class XDetails
{
String xColumn1;
String xColumn2;
YDetails relatedY;
...
}
class YDetails
{
... fields of Y ...
}
Then you can have an array or List<XDetails>

You cannot create an instance of an array of a generic type using new.
One alternative is this:
import java.lang.reflect.*;
import java.util.*;
public class Test
{
public static void main( String args[] )
{
List<String[]> x = ...;
List<List<String[]>> yElements = Arrays.asList(
(List<String[]>[])Array.newInstance(List.class, x.size()));
}
}
Related question: How to create a generic array in Java?. (The example there is about creating an instance of an array of a generic type parameter ... but the same approach applies here.)
However, I think that this whole question is based on an incorrect assumption.
I also want to tell you that I MUST have a fixed lenght list to store a List of String[ ] in a specific index of this List of Lists.
You don't HAVE TO have a fixed sized list. From the computational perspective, your code would work just fine with a non-fixed sized list ... provided that you don't add or remove list elements. (In fact, using Arrays.asList to wrap an array won't stop some other code trying to add / remove elements ...) Anyway ... if you just make the implementation type ArrayList<ArrayList<ArrayList<String>>>, then the generic array creation problem goes away.
In addition, I suspect that it is incorrect to use x.size() as the size of yElements. The size of yElements probably should be determined by the number of x instances there are going to be, not the size of a given x instance.

Related

Why Do we have TwoPlusArrayList and OnePlusArrayList inside Lists class?

I am just curious about the Lists class implementation of google guava, we have two methods to create List from Array,
Lists.asList(E first, E[] rest)
Lists.asList(E first, E second, E[] rest)
Why do these methods has first and rest separately? cant it be like Arrays.asList implementation of java ?
The only thing I am able to see is the first and second is nullable and rest is not nullable
Can anyone help to understand this ?
Ok, so the job of the Lists.asList() is not exactly to directly convert an array to a list.
Suppose we have an array, and we want to insert an element to it, we can’t do it as the array size is fixed. One solution to this problem is to allocate an new array of +1 the size of the original array and copy all elements from the original array to the new array. This works but it is highly inefficient.
Guava provides an efficent solution to this problem – Guava’s Lists.asList() method returns an unmodifiable list backed by the original array which also contains the specified element.
source: https://www.techiedelight.com/guava-lists-class-java/
So basically, you can use it to just convert an array by giving the first and/or second parameters (depending upon what method you are using) as null, and giving the "rest" parameter as your array.
This will return your array as list, perhaps with null as the first index (and second as well, depending on what you are using)
But if you want, you can use the same methods to get a list with some specific data appended to your array (at first and second index values)
Hope this was helpful!
The main reason these methods exist is to help you when you write a method with a signature like
void foo(Bar first, Bar... rest);
which is something you'd do when you want to allow the user to call the method as if it were a method with just a varargs parameter, but you want to require that it be called with a minimum of one or two arguments (whereas varargs alone would allow them to call it with zero). In the implementation of such a method, you might want to treat those arguments as a single list. Lists.asList does that without doing any array copying:
void foo(Bar first, Bar... rest) {
List<Bar> bars = Lists.asList(first, rest);
// ...
}

Storing 15,000 items in Java

I have a document with 15,000 items. Each item contains 6 variables (strings and integers). I have to copy all of these into some sort of two dimensional array, what the best way to do it?
Here are my ideas so far:
Make a GIANT 2D array or array list the same way you make any other array.
Pros: Simple Cons: Messy(would create a class just for this), huge amount of code, if I make a mistake it will be imposable to find where it is, all variables would have to be string even the ints which will make my job harder down the road
Make a new class with a super that takes in all the variables I need.
Create each item as a new instance of this class.
Add all of the instances to a 2D array or array list.
Pros: Simple, less messy, easier to find a mistake, not all the variables need to be strings which makes it much easier later when I don't have to convert string to int, a little less typing for me Cons: Slower? Will instances make my array compile slower? And will they make the over all array slow when I'm searching to items in it?
These ideas don't seem all to great :( and before I start the three week, five hour a day process of adding these items I would like to find the best way so I won't have to do it again... Suggestions on my current ideas or any new ideas?
Data example:
0: 100, west, sports, 10.89, MA, united
*not actual data
Your second options seems to be good. You can create a class containing all the items and create an array of that class.
You may use the following:
1. Read the document using buffered reader, so that memory issues will not occur.
2. Create a class containing your items.
3. Create a List of type you need and store the elements into it.
Let me know in case you face further problems.
If you already have the document with the 15000 * 6 items, in my experience you would be better served writing a program to use regex and parse it and have the output be the contents of the java array in the format you want. With such a parsing program in place, it will then also be very easy for you to change the format of the 15000 lines if you want to generate it differently.
As to the final format, I would have an ArrayList of your bean. By you text thus far, you don't necessarily need a super that takes in the variables, unless you need to have subtypes that are differentiated.
You'll probably run out of static space in a single class. So what I do is break up a big class like that into a file with a bunch of inner nested classes that each have a 64K (or less) part of the data as static final arrays, and then I merge them together in the main class in that file.
I have this in a class of many names to fix:
class FixName{
static String[][] testStrings;
static int add(String[][] aTestStrings, int lastIndex){
for(int i=0; i<aTestStrings.length; ++i) {
testStrings[++lastIndex]=aTestStrings[i];
}
return lastIndex;
}
static {
testStrings = new String[
FixName1.testStrings.length
+FixName2.testStrings.length
+FixName3.testStrings.length
+FixName4.testStrings.length
/**/ ][];
int lastIndex=-1;
lastIndex=add(FixName1.testStrings,lastIndex);
lastIndex=add(FixName2.testStrings,lastIndex);
lastIndex=add(FixName3.testStrings,lastIndex);
lastIndex=add(FixName4.testStrings,lastIndex);
/**/ }
}
class FixName1 {
static String[][] testStrings = {
{"key1","name1","other1"},
{"key2","name2","other2"},
//...
{"keyN","nameN","otherN"}
};
}
Create a wrapper (Item) if you have not already(as your question does not state it clearly).
If the size of the elements is fixed ie 1500 use array other wise use LinkedList(write your own linked list or use Collection).
If there are others operations that you need to support on this collection of items, may be further inserts, search( in particular) use balanced binary search tree.
With the understanding of the question i would say linked list is better option.
If the items have a unique property (name or id or row number or any other unique identifier) I recommend using a HashMap with a wrapper around the item. If you are going to do any kind of lookup on your data (find item with id x and do operation y) this is the fastest option and is also very clean, it just requires a wrapper and you can use a datastructure that is already implemented.
If you are not doing any lookups and need to process the items en masse in no specific order I would recommend an ArrayList, it is very optimized as it is the most commonly used collection in java. You would still need the wrapper to keep things clean and a list is far cleaner than an array at almost no extra cost.
Little point in making your own collection as your needs are not extremely specific, just use one that is already implemented and never worry about your code breaking, if it does it is oracles fault ;)

Partially filled array, deleting duplicate array

I am doing one exercise in Absolute Java.
The Question is: Write a static method that has a partially filled array of characters as a formal parameter and that deletes all repeated letters from the array. The method should have two formal parameters: an array parameter and a formal parameter of type int that gives the number of array positions used. When the letter is deleted, the remaining letters are moved one position to fill in the gap.
What I think of is using hashset, it should be the most easiest way.
And another way that I am thinking is converting array to list , deleting the duplicates element and then transfer it back.
Here is a problem for me: how to write that code?? (why I am asking it?)
public static char[] deleteRepeats(char[] array, int size)
{
ArrayList<String> newarray = new ArrayList<String>();
newarray = Arrays.asList(array);
}
it says type mismatching, how can I correct the code?
Another question is: Back to the initial question, how to use partially filled array to implement it?
ArrayList<String> newarray = new ArrayList<String>();
Is an array list of Generic type String. However your parameters are of char type. Therefore they are not interchangeable. That's whats throwing the Type Mismatch error.
You are right using a Set is the easiest way to implement it. However I don't know whether the exercise wants you to manually do the work.
However you if you cannot use the wrapper class Character and must use the char type then you must do manual conversion if you are going to get a Set to do your replacement work for you.
EDIT:
You cannot use Arrays.asList() method to get a list like that. That method takes java objects as arguments not primitive types. And when you pass the char[] the only object it sees is the array itself.
So the result is a List<char[]> since generics do not support primitive types.

Creating a list from size

I know this is easy and can be done with 2 lines of code, but i am curious to know if there exists any such function
i have a int which tell me the size of list and i need to create a list say
List<Integer> intList;
i can create this by easily iterating through the size something like
for(int i=1 ; i <= size; i++) // started with 1 as i want it from 1
{
fill list
}
but i was just thinking as if there exists any such methods either in Collection API or Apache common
where i can pass the size to get a List with given size
Edit
May i was not able to put question in proper way, i want to get filled my list say
if size=4 than i was thinking abt something
Integer=1
Integer=2
Integer=3
Integer=4
and not an empty list with size 4
i know question do not make much sense, but still its better to clear your questions
Short answer: No
The two-liner you're currently using is already optimal.
The thing here is that List is an interface class and you can't create instances of an interface class. So before you want to construct it you need to know what kind of List you want to create. For the moment let's assume you want an ArrayList. From this moment on you can simply use the correct constructor to initialize your list e.g.
List<Integer> intList = new ArrayList<Integer>(10);
Which constructs an ArrayList of initial capacity 10.
For other kinds of list you can check the Java documentation.
To fill the list with initial data you can do something like this:
int[] myArray = new int[]{ 58,63,67,72,70,63,62,63 };
List<Integer> intList = new ArrayList<Integer>(myArray );
To answer the question after what you've added with your edit: No, there's no such method to fill a list with ascending integers in the standard collections API. You'll have to program a loop yourself and add elements to the list.

Java: fillings two vectors and sorting them

How can I fill up two vectors and combine them with each other (either index or an object type in class). I guess if I use index to combine them, then the sorting can be handled with Collections.sort otherwise I have to create a comparator.
We have to code down to the Java 1.4 convention.
To make your imagination easier; it's a grid which has a sorting vector (rows) and a content vector (with all cols). They need to be filled in a vector and sorted.
Context: I have a GridBagLayout containing all components in a wierd order. I need to cycle through all components and fill them in the right grid order (gridx, gridy). For that solution I thought about two vectors, one defines the row and points to the vector containing it's cols. Either the sort will be be resolved while filling the vector or I have to sort it in a second step. I guess for java 4 there is no other approach than two vectors containing an object, right?
The OO solution is to wrap the objects in both vectors in something that implements the comparing and keeps a pointer to the real object. This way, you can sort both vectors independent of each other and use the wrapper to get at the real object.
This is the "Decorator" design pattern.
Please let me know if I understand. As input, you're given two vectors. The first is an ordered list of row numbers that reference indices in the second vector. The second vector is a list of somethings. You would like a vector that contains the same objects as the second vector, but sorted in the order described in the first vector.
Assuming that's what you're trying to do, this is how I'd do it:
public class ThisHadBetterNotBeAHomeworkAssignmentYoungMan {
public Vector orderContent(Vector indices, Vector content) {
Object[] orderedStuff = new Object[content.size()];
for( int i=0; i < indices.size(); i++ ) {
orderedStuff[i] = content.get(((Integer)indices[i]).intVal());
}
return new Vector(orderedStuff);
}
}
//Note that this is pretty rough code, and I have neither executed it nor bothered checking to see if you can pass an array of stuff into a Vector as a constructor, but you get the idea.
//note also that I'm not sure exactly what you're asking and could be entirely wrong.

Categories