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.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
Why can't I add null in the list of model data arrays in Kotlin language?
enter image description here
adapterPaging!!.setOnLoadMoreListener {
var customersModels: List<CustomersModel> = ArrayList()
customersModels.add(null)
}
var customersModels: List<CustomersModel> = ArrayList()
Your problem(?) here is polymorphism. You've defined customersModels as a List, which in Kotlin is explicitly immutable. You can't add things to it.
Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.
You're assigning an ArrayList to that variable, which is an object that does have the add method. And an ArrayList is a List, so you can do that. Like how a pencil is a writing tool that's erasable, if someone just needs something to write with, you can give them a pencil or a pen. All they've asked for is something that writes.
But the variable you're interacting with, customersModels, is explicitly a reference to a Kotlin List - a more restrictive subtype of MutableList*. It knows nothing about what that object actually is, just that it fits the immutable List type. That type does not have an add method so you can't call it. Same as how if you ask for a writing tool, you can't assume you'll be able to erase what you write.
So you have three options here (let's not get into reflection):
You can cast that variable to another type:
// or 'as ArrayList' if you really need to be that specific for some reason - you probably don't
(customersModels as MutableList).add(thing)
This is an unchecked cast - you're telling the compiler "hey I know what this is, you don't but you're just gonna have to trust me on this one". This is unsafe, because there's no protection, the compiler can't do any checking and force you to handle potential problems. (Don't do this)
A better approach is to actually check as you cast - there are two ways to do this in Kotlin:
// confirm the object's type - this will result in a 'smart cast' because the compiler
// can see that you're handling it safely, so it basically allows you to treat
// myList as that type
if (myList is MutableList) myList.add(thing)
// same deal but you can cast with a null fallback if it fails, then null-check the result
(myList as? MutableList)?.add(thing)
This is good for things where you handle a more general type, but you might want to get specific and handle different member types in different ways. Especially common if you're using sealed classes.
The last approach is to just use the appropriate type in the first place!
// MutableList, since you want to mutate it by adding stuff
var customersModels: MutableList<CustomersModel> = ArrayList()
customersModels.add(null)
You're creating a list you want to change - so that's a MutableList, and that's what customersModels should be. This kind of thing can be internal - you can expose that list as a List rather than a MutableList, so that other stuff that uses it sees it as a fixed, immutable list. If you've used LiveData you've probably seen this approach:
private val _myData = MutableLiveData<String>("hi")
val myData: LiveData<String> = _myData
myData is literally pointing at that MutableLiveData object, but because its type is just LiveData (the immutable kind) that means stuff that accesses that public variable see an object they can't change. Really they could cast it to MutableLiveData and mess with it, but it's less a security feature and more of an organisational thing. Make it clear how stuff is meant to be used, how you interact with it, etc. If you want to update, go through a specific function, that kind of thing.
So use List if it's just a list that's meant to be read, not written to. If it will/might be changed, use the MutableList type. This makes it clearer about what's going on.
Also, generally you shouldn't use explicit types like ArrayList - Kotlin has a bunch of functions to generate Lists and MutableLists, which makes it easier to reason about what you're doing and why:
val numbers = List(5) { it + 1 }
val greetings = mutableListOf("hi", "hey", "sup")
Notice I'm not specifying the type next to the variable, it's getting inferred by the function I'm using. So there's no "treat this mutable list as an immutable one" going on (unless you need to do that for a specific reason!)
Your customersModel POJO class must contain a nullable data type. and also you have to declare list as follow :-
var customersModels: ArrayList<CustomersModel?> = ArrayList() CustomersModel must be Then you will add null values to the list.
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.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I believe Array and ArrayList both are non-Synchronised;behave same in multiThreaded env.
And both are Index based. Only Adavantage is ArrayList has utility methods and flexible.
Apart from those Utility methods only to get and set fixed no of Objects which is best in java? Is there any overhead in using Arraylist than Array? Pls explain.
Let us consider Scenario like
1) 1,00,000 Objects to be stored.
2) 1,00,000 primitives to be stored
To be able to answer question on which data representation fits better, one needs to know many details like:
how many elements will be stored in the structure?
will the structure be mutable or immutable, that is, will the contents of the it change after initialization?
do you know the final size of your structure when you initialize it?
how will you access the elements? iterate over it? random access by index?
etc.
Regarding the array vs. arraylist: arraylist performance overhead is minimal and in most cases it is not significant. On the other hand, it is more flexible. see this thread Array or List in Java. Which is faster?
ArrayLists will have an ever so slightly higher overhead than an array. This is because an ArrayList is just a wrapper for an array with a few convenience methods added. Though if you know exactly how many elements you will ever have then ArrayList doesn't add much.
The biggest advantage of having an array over an ArrayList (at least in Java), is the cleaner syntax. eg.
myArray[0] = x;
// as opposed to
myList.set(0, x);
// personally I can never remember the order for the arguments and I have to check
Adding all the elements to another list
One possible advantage to ArrayLists is being able to easily add all the elements in an ArrayList to another list.
anotherList.addAll(myList);
However, the same can easily be accomplished by using the Collections util class.
Collections.addAll(anotherList, myArray);
Immutability
One problem is that arrays are mutable (element values can be changed), but you may only want to present a immutable view of your collection of elements to classes outside your own class. Here lists can be useful again.
List<E> readOnly = Collections.unmodifiableList(myList);
But in this case also Arrays can still easily be used to to back an immutable list.
List<E> readOnly = Collections.unmodifiableList(Arrays.toList(myArray));
Synchronized access
Finally, and most importantly, you can make use of the Collections class to make your Lists synchronized.
List<E> syncedList = Collections.synchronizedList(myList);
You could wrap your array in a list and make access synchronized, but then you'd still have to use access via the list, so there wouldn't be much point in having an array.
Final word - Personal preferences
In general though, the whole thing comes down to preference. What is your personal preference, do you prefer working with arrays or Lists? Personally I prefer lists because they work better with the rest of the collections API and making a generic Lists is easy, making generic arrays is a real pain.
List<E> list = new ArrayList<E>(); // easy
E[] array = new E[]; // compilation error
A ArrayList uses internally an Array. So yes, an ArrayList has a little bit of overhead, but it provides you with some convienent methods to access the elements in the list. It depends what you prefer.
If count of Objects is fixed, obviously Array is better solution. Because ArrayList uses array which can be created several times during adding.As javadoc says in array list function
Each ArrayList instance has a capacity. The capacity is the size of
the array used to store the elements in the list. It is always at
least as large as the list size. As elements are added to an
ArrayList, its capacity grows automatically.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Benefits of arrays
Hey there,
are there any reasons to prefer Arrays (MyObject[]) over ArrayLists (List<MyObject>)? The only left place to use Arrays is for primitive data types (int, boolean, etc.). However I have no reasonable explanation for this, it just makes the code a little bit slimmer.
In general I use List in order to maintain a better flexibility. But are there reasons left to use real Arrays?
I would like to know,
best regards
I prefer to use Arrays over ArrayLists whenever I know I am only going to work with a fixed number of elements. My reasons are mostly subjective, but I'm listing them here anyway:
Using Collection classes for primitives is appreciably slower since they have to use autoboxing and wrappers.
I prefer the more straightforward [] syntax for accessing elements over ArrayList's get(). This really becomes more important when I need multidimensional arrays.
ArrayLists usually allocate about twice the memory you need now in advance so that you can append items very fast. So there is wastage if you are never going to add any more items.
(Possibly related to the previous point) I think ArrayList accesses are slower than plain arrays in general. The ArrayList implementation uses an underlying array, but all accesses have to go through the get(), set(), remove(), etc. methods which means it goes through more code than a simple array access. But I have not actually tested the difference so I may be wrong.
Having said that, I think the choice actually depends on what you need it for. If you need a fixed number of elements or if you are going to use multiple dimensions, I would suggest a plain array. But if you need a simple random access list and are going to be making a lot of inserts and removals to it, it just makes a lot more sense to use an Arraylist
Generally arrays have their problems, e.g. type safety:
Integer[] ints = new Integer[10];
Number[] nums = ints; //that shouldn't be allowed
nums[3] = Double.valueOf[3.14]; //Ouch!
They don't play well with collections, either. So generelly you should prefer Collections over arrays. There are just a few things where arrays may be more convenient. As you already say primitive types would be a reason (although you could consider using collection-like libs like Trove). If the array is hidden in an object and doesn't need to change its size, it's OK to use arrays, especially if you need all performance you can get (say 3D and 4D Vectors and Matrices for 3D graphics). Another reason for using arrays may be if your API has lots of varargs methods.
BTW: There is a cute trick using an array if you need mutable variables for anonymous classes:
public void f() {
final int[] a = new int[1];
new Thread(new Runnable() {
public void run() {
while(true) {
System.out.println(a[0]++);
}
}
}).start();
}
Note that you can't do this with an int variable, as it must be final.
I think that the main difference of an array and a list is, that an array has a fixed length. Once it's full, it's full. ArrayLists have a flexible length and do use arrays to be implemented. When the arrayList is out of capacity, the data gets copied to another array with a larger capacity (that's what I was taught once).
An array can still be used, if you have your data length fixed. Because arrays are pretty primitive, they don't have much methods to call and all. The advantage of using these arrays is not so big anymore, because the arrayLists are just good wrappers for what you want in Java or any other language.
I think you can even set a fixed capacity to arraylists nowadays, so even that advantage collapses.
So is there any reason to prefer them? No probably not, but it does make sure that you have just a little more space in your memory, because of the basic functionality. The arraylist is a pretty big wrapper and has a lot of flexibility, what you do not always want.
one for you:
sorting List (via j.u.Collections) are first transformed to [], then sorted (which clones the [] once again for the merge sort) and then put back to List.
You do understand that ArrayList has a backing Object[] under the cover.
Back in the day there was a case ArrayList.get was not inlined by -client hotspot compiler but now I think that's fixed. Thus, performance issue using ArrayList compared to Object[] is not so tough, the case cast to the appropriate type still costs a few clocks (but it should be 99.99% of the times predicted by the CPU); accessing the elements of the ArrayList may cost one more cache-miss more and so (or the 1st access mostly)
So it does depend what you do w/ your code in the end.
Edit
Forgot you can have atomic access to the elements of the array (i.e. CAS stuff), one impl is j.u.c.atomic.AtomicReferenceArray. It's not the most practical ones since it doesn't allow CAS of Objec[][] but Unsafe comes to the rescue.
I have the following problem in my Data Structures and Problem Solving using Java book:
Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.
First, I believe it is asking you to write a method. Like:
void printReverseList(Collection col) {}
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).
That could technically count as 1 routine (all have the same name).
I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.
You might want to read this.
Isn't there a base Collection class?
Probably worth looking here as a starting point: Collections.