Java: fillings two vectors and sorting them - java

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.

Related

Guava Table vs. 2D array

What is the difference between using a Guava Table implementation and a 2D array if I know the size of the array beforehand?
Is one more efficient than the other? How?
Would it make a difference in running time?
The most obvious and crucial difference is that an array is always indexed, with ints, whereas a Table can be indexed with arbitrary objects.
Consider the Table Example from the Guava site:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
...
The indexing here happens via Vertex objects. If you wanted to do the same with an array, you would have to add some getIndex method to the Vertex class, and accesss the array like this
double array[][] = new double[4][5];
array[v1.getIndex()][v2.getIndex()] = 4;
This is inconvenient and particularly hard to maintain - especially, when the indices may change (or when vertices have to be added/removed, although you mentioned that this is not the case for you).
Additionally, the Guava table allows obtaining rows or columns as separate entities. In a 2D array, you can always access either one row or one column of the array - depending on how you interpret the 2 dimensions of the array. The table allows accessing both, each in form of a Map.
Concerning the performance: There will be cases where you'll have a noticable difference in performance. Particularly when you have a large 2D array of primitive types (int, double etc), and the alternative would be a large table with the corresponding reference types (Integer, Double etc). But again, this will only be noticable when the array/table is really large.
Additionally to what Marco13 said, read this: https://stackoverflow.com/a/6105705/1273080.
Collections are better than object arrays in basically every way
imaginable.
The same applies here. A 2D array is a low-level tool that might be needed when you need some high-performance structure for primitives. However, arrays have no meaningful methods, no behaviour, no nothing, and therefore are usually an underlying data structure in classes that add some behaviour to them. Do this with a 2D fixed-size array and you'll end up with ... a Guava-esque Table.
Also, a Table can be a 2D-array, or a Map<R, Map<C, V>>, in the future we might also have resizable Table implementations - all within one interface.
Regarding the performance - you should almost always go for the more high-level approach to get code as readable and clear as possible, then measure the performance and only if it's problematic, go for different approaches.

How do I choose random objects of the same type from a vector array of differing types?

Let's say for example a vector is composed of some objects, one of type rectangle, some of type triangle, and then circles.
v = [rectangle, triangle, triangle, circle, circle]
The vector's size can change. I can add another circle as so:
v.addElement(circle);
and..
v = [rectangle, triangle, triangle, circle, circle, circle]
but each object type is clustered together like above. It can't be like:
v = [rectangle, circle, circle, triangle, circle, triangle] //<-- can't be.
I know I explained it pretty horrible but hopefully, it's enough to understand my scenario. Now, I want to randomly choose, for example, an object of type circle.
My thought process is to make a separate method that 1, finds the beginning index and 2, find the ending index and then use random functions off of that. Is there a more elegant way to solve this problem of only choosing randomly off of circles?
Use the Collections API:
Collections.shuffle(v);
Object random = v.get(0);
You should use a hashmap and map the object class as the key and a corresponding array of objects of that class. You can yse reflection to get the class name and set as the key, then add the object to the array as the value.
Otherwise you can't group similar objects in the array and choose a random object from a set of similar objects in an array of different classes like you asked... Unless you framed your question incorrectly
This sounds like a fairly simple random pick problem. All you need to do is generate a random number and get that element -
v.get(Random.nextInt(v.size()));
You can potentially use the implements keyword to check if an object is of a type (or a subtype of that type), but this is not a very pretty solution.
The best solution would likely be to control read and write access to this vector; basically, if you have specific methods for inserting the different shapes, you can stay in control and always ensure that things are inserted to the right place. At that point, just store two ints or such to know where the second and third sections start when choosing.
Although personally, I would just use three separate vectors, if that's possible.

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 ;)

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

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.

Comparing functionality between Vectors and Arrays in Java

I've been thinking about this one for a long time. What is the difference between Vectors and Arrays? I know they do similar things, if not exact.
String Array
String[] array = new String[4];
String Vector
Vector<String> vector = new Vector<String>(4);
It seems kind of redundant to me why there would be both arrays and vectors. Are there any advantages or disadvantages to using one or the other?
Vectors are resizable. Arrays are not.
The difference is that 'Vector' is an extension by programmers, whereas an array is a built-in function of the language itself.
You can edit how the Vector behaves (by editing its source code), whereas an array is defined by the compiler.
And obviously, Vectors can be potentially sized (depending on implementation). Arrays are static and cannot be resized - you have to recreate it and copy the data over.
Vector is synchronized. Arrays are not(?).
Array cannot be re-sized, while Vectors can.
Vector uses Arrays internally. The main advantage of a Vector compared to an Array is its automatical increase of capacity. An Array keeps its size once created, a Vector does not
It seems kind of redundant to me why there would be both arrays and
vectors
For one, Vectors can be resized. If you declare an array of size 10, you are left with 10 always, unless you copy the contents to another larger sized array. Methods of Vector are synchronized.
Vectors are part of the collections framework. Vector is a List. There are other lists, ArrayLists, LinkedLists etc with specific features. There are Sets and Maps. All of them hold "lists" of items, but each of them give specific advantages in specific situations.
You might want to read about java collections.
Vectors will automatically resize for you to accommodate as many entries as you want in them. An array is fixed in size, and will give you an OutOfBounds exception when you try to add more than you allocated.
When you provide the size for a vector, that's just the original size it starts with. It'll automatically grow/shrink as necessary.
1- Vectors are resize-able, arrays are not
2- Vectors are responsible for memory allocate and release, arrays are not. This makes vectors safer to use than arrays.
3- Vectors have a good performance on their implemented functions, which you may not reach by your own programming with arrays.
4- Finally I think it's wiser to use vectors, most of the times.
An array is a basic java data structure, whose size is fixed when defined.
A Vector is part of the Java Collections Framework, and contrary to your beliefs, or not even close to the same thing as an array. Among many other things, Vectors are resizable and can interact with other collections.
Java array types are not necessary. They actually create a lot of problems. Avoid them if you can.
We could do better to replace them with a standard class Array<T>. Some new post-Java languages are taking this approach.
(History alert) In the old days, Java didn't have generics, a non-generic collection class would suck to use (with lots of castings). Then array types were really poor man's generics because they carry element type info. That's why many methods return arrays, instead of List.
I think the above suggestion is not good. Check this link to get brief idea.
Difference b/w Array and Vector
Vectors help to insert and delete elements easily while arrays helps to sort and access elements with ease.
Vectors can hold different type of elements
Arrays only the type defined when forming them
You can use array list which is some what similar to vector and provided much better features

Categories