How can I add an Array into a Queue? - java

Is it possible to add an array into specifically, a ConcurrentLinkedQueue? If so, how exactly would the .add statement look like?
THIS IS HOMEWORK RELATED, however, my entire program is meant to perform calculations on MyObjects (the default constructor of MyObjects generates random values to perform a ton of calculations on).
For example:
//Note: I couldn't use the Diamond Braces for the Queue-type when posing this question
ConcurrentLinkedQueue theLinkedQueue {MyObjects[]} =
new ConcurrentLinkedQueue{MyObjects[]}();
MyObjects[] theArray = null;
for(int i = 0; i < 100; i++){
theArray = new MyObjects[CONSTANT_SIZE];
theLinkedQueue.add(theArray(objparameter1, objparameter2));
}
The program implements multi-threading and in my thread class I've passed the Queue into the constructor, and am attempting to take off a MyObject array which a MyObject temp will point to, but so far I'm only capable of adding a single MyObject to my Queue at a time and pulling it. I want to be able to add the same amount of MyObjects as individual components rather than individually. I've attempted various lines of code only for NetBeans IDE to recommend a method to throw an UnsupportedOperation Exception. How could I add arrays into my ConcurrentLinkedQueue?
(Also apologies if my question is dense or confusing, first time posting here).

The correct syntax for the declaration of your queue is:
ConcurrentLinkedQueue<MyObjects> theLinkedQueue = new ConcurrentLinkedQueue<>();
Start with that and see how things go from there.

I figured out the solution, which was simply to add the array without 'objparameters' included.
theLinkedQueue.add(a); //where a was a 'MyObject' array.
I presumed you had to load the parameter to be passed for each array index, which seems pretty silly.

Related

Arraylists without loop

I am learning Java and I am wondering one thing:
Do I need for-loops for arraylist, before one can consider it as arraylist? Because every example I find, shows me some sort of a loop.
So will you consider this as arraylist?
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Item");
And then use the elements from the list in methods etc.
Or is this better(even if the first example is good enough for you):
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Item");
for (int i = 0; i < stringList.size(); i++)
String item = stringList.get(i);
System.out.println("Item " + i + " : " + item);
}
No, you do not have to use loops when using collections. There's nothing wrong with not using loops. Although, in almost every situation where you're going to use some sort of collection, you're going to want to be using some sort of a loop.
One exception I might see where you need to use a collection and definitely won't loop with it is if you're using a method that takes a collection as an argument and you can't override, but you want to perform whatever operation on a single object.
In this case, you could load an ArrayList with a single string so that that single string could be sent to the method via the collection.
Also, in both Android and iOS programming, you will frequently see some sort of collection used in order to save user settings, and these aren't necessarily used in loops.
Just because a list has only 1 element doesn't mean it is no longer a list. Loops are found with all collections because iterating through a list is usually the reason you needed a list in the first place. If you know your list only has 1 item then you don't ever need a loop, you can just System.out.println(stringList.get(0)).
You absolutely do not need to use loop control structures when dealing with collections. Often you can write cleaner collection-manipulating code using a library like Guava.

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

How to correctly clear list in java

Lets say I have a list like this:
private LinkedList<String> messages = new LinkedList<String>();
When my method gets invoked for the first time there some strings added to this list. And I have also another method in which I need to clear this list from previously added values. To clear it I can use:
messages.clear();
This will remove all the elements from the list. Also I can create a new instance like this:
messages = new LinkedList<String>();
Which way is more proper to clear the list?
messages.clear();
Will actually clear the list, messages = new LinkedList<String>(); will just set messages as referencing a new list instance, so you could argue the first way is more "correct" to clear the list instance.
Say you have a list that is referenced by two variables, a and b. Like this (they don't have to be as close to eachother as this, they might even be in different files..):
final List<String> a = new LinkedList<String>();
final List<String> b = a;
Now, there is a big difference between
a.clear();
which will make both a and b reference the same, empty list, and
a = new LinkedList<String>();
which will make 'a' reference a new, empty list, and 'b' the old, populated list. (So they do not reference the same list).
Since you probably want them to reference the same list, a.clear() is preferred, since you won't get any surprises when your looking at the list referenced by b (which you might believe to be empty, but turns out to be populated if you use the new-approach).
I prefer the first approach i.e. messages.clear(); as it clear the elements but the List is not destroyed and recreated. All elements are removed as desired.
One side effect is there though: It iterates your list and removes one item at a time so if the list is huge then it's an unnecessary overhead.
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
Same way second approach has also one side effect: If you are using the object reference of you r list somewhere else in your program, that needs to handled properly otherwise you could get some unwanted surprises e.g. if you added your list to some other object/variable, then first approach will clear that elements from every place where it was referenced while second will not.
Summary: Both the approach outcomes are different in low level nature; though they seem to to serve your high level requirement (clearing the list). Decide carefully based on your low level requirements.
They are almost similar, but I would say messages.clear() is more flexible.
The second approach is simple and much used, but the problem where you have final modifier on your list you can not clear it that way.
messages.clear();
is more efficient. For more safety you can ask if this list is not empty befor
Personnaly I prefere to use LinkedList#clear because it is more clearly to understand during reading the code what you are doing.
But the new LinkedList<String>(); will work fine as well. So it's up to you what to use!
It clearly depends upon your need.
If you want to keep reference to your list object instance (as an example if that clear method is called inside a method in which the messages is a parameter, then the call to .clear() is the best solution.
On the other hand, if the list you want to clear is a member field (or a local variable in a method) of the object the current method is a member of, then you can call new LinkedList<String>(); without any trouble.
Notice that, to avoid the first (which I tend to disapprove), i usuall always return obejcts I modify as results from methods modifying them.
the first one is preferable. the second one makes some extra burden on the garbage collector. but the first one not.

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.

Adding all wrong answers into an array with Java - how?

I want to take all the questions that were answered incorrectly (it's a simple program asking math questions) and if they got the question wrong, add the question number to the array for further use.
But, I don't know how long this array will be, it could theoretically be of a different length each time the program is ran. So how would I set up the array?
You should use an ArrayList instead.
You could do something like:
ArrayList<String> wrongAnswers = new ArrayList<String>();
// Call this function with the user's answer as a parameter, when the answer
// has been determined to be incorrect.
public void wrongAnswer(String answer) {
wrongAnswers.add(answer);
}
public void printWrongAnswers() {
System.out.println("Wrong answers:");
for (String answer : wrongAnswers) {
System.out.println(answer);
}
}
Start with an ArrayList and then you can call toArray() to get an actual array.
You can also initialize an array whose size is the number of questions you have. Then keep a running count of missed questions, and simply trim the array at the end.
Look into using an ArrayList. This is an implementation of the List interface that is backed by an array.
Using the default constructor, it will start with a backing array of size 10 (but don't worry too much about this detail):
List<Question> questionList = new ArrayList<Question>();
You can then add elements:
questionList.add(question);
It will then resize this array as needed as you continue to add elements.
Since you probably know how many questions you are going to ask, you can stick to the array if you like and make it exactly as long as the number of questions you have. I would like to see the first person who succeeds in answering more questions incorrect then the number of questions available on the test
Use a collection, like a List implementation (like ArrayList), instead of an array. Then you can add by calling list.add(miss) and never worry about the size.
Do you specifically need an array? You can get the array, but in general, it's rare to specifically need one for requirements like these.

Categories