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.
Related
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.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm developing some methods here, some of them needs to have a list as a parameter.
I want to know if the appropriated way to do this is to use a List< T > or use an array [ ].
For example:
void method_name(List< String > arg)
void method_name(String arg[])
Which one is the recommended option?
Can someone help me?
Remember that List<T> is an interface. So passing a List as an argument makes your code more flexible since it does not depend on a specific implementation of a List.
So a method that takes a List<String> as a parameter can actually take an ArrayList<String> or a LinkedList<String> or any other implementation of the List interface. So it could even take a parameter of type MyList<String>, as long as the class MyList declares that it implements the List interface. The benefit of this is that if you wanted to change from using an ArrayList to a LinkedList elsewhere in your code, this method would still work.
By contrast, a method that takes a String[] can only take a String[]. So you would no longer have the benefit of being able to change the way you store these strings elsewhere in your code, without also having to change the method.
In terms of why Google might be using arrays as parameters a lot in their APIs, I think it really comes down to what they are using them for.
So I can't really recommend one or the other. It really depends on what the method does and what you want to do with the collection. For an overview of the key differences between modern programming structures, like Lists, and good old fashioned arrays, take a look at this answer.
There isn't a recommended or standard option. Lists and arrays are not the same object types at all. Both are used throughout Java. You can do either or both (overloading by type).
Keep in mind that there is a third option available namely
void method(String... params)
I can be accessed like an array however the size is flexible and you do not have to put everything into an array before the method call, but simple pass all your Strings.
method(string1, string2, string3);
i think more popular is array parameter.
void method_name(String arg[])
you can get any element from array andunderstand how many elements in array.
I think you should use List. it is slower, but it offers more flexibility and it's easier to use, especially if you are going to resize them.
If your parameter list is fixed just use as many parameters as you need
method(String parameter1, String parameter2)
I find using Arrays is cumbersome. There are several shortcomings:
No generics, see here
you have to copy the whole array into a new bigger one if you want to enhance it
and more depending on what you want to do
Especially when you want to use Lists in your code you have to copy your content all the time. So I'd say to go with List.
method(List<String> parameterList)
There is mentioned another way using variable parameter lists (varargs). However, be aware that you cannot pass the vararg parameter simply into another method using varargs as the vararg parameter is represented as an array and will be passed as such.
method1("first", "second");
void method1(String... params) {
//params[0] will be "first"
//params[1] will be "second"
method2(params);
}
void method2(String... params) {
//params[0] will be an array of Strings
//params[1] will give you an OutOfBoundsException
}
It completely depends on how you are going to use these objects.
Use List when
1) You are going to perform sorting, searching etc but not want to write much lines of code
2) If the size of elements may increase because Lists are resizeable.
Use Array if your requirement is not as above.
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 ;)
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.
Antescript: I'm aware that there's a prior SO question whose title sounds like it refers to the exact same question. It doesn't.
Anyway, this question is a little weird - there are plenty of better ways to work around the issues here, but I'm curious as to how I could solve my particular dilemma.
Let's say I have a method that uses varargs to accept an arbitrary number of elements, perhaps of type Integer. If I have an arbitrary-length array of Integers, is there a way for me to call my method with a comma-separated param list composed of each element of said array?
Here's a brief, contrived example:
Integer[] paramList = new Integer {1, 2, 3};
varMethod(paramList[0], paramList[1], paramList[2]);
// varMethod({{for (param : paramList) {param;}}});
public void varMethod(Integer...values) {
for (Integer value : values) {
foo(value);
}
}
That commented-out line hints at what I want to do. Since the paramList integer is arbitrary length, calling varMethod with each element explicitly requested (line 2) won't work. What I'm wondering is if there's a way to dynamically generate the comma-separated param list from the elements of an array.
Again, I realize that in an example like this, there are better ways to approach the entire problem, but please be aware that I've simplified the code so that it's only relevant to the particular issue we're discussing here. Any workarounds that address my posted code won't generalize to the problem I'm really working on that led me to formulate this question in the first place.
I think you're just looking for:
varMethod(paramList);
Perhaps you didn't realize that Integer... is a special variant of a normal Integer[] array. Thus since paramList is already an Integer[] array, you can just pass it directly into the method.
You can just call
varMethod(paramList);