Storing string arguments array in a list :java - java

Essentially, I want to have a method:
public void setArgs(String... vals)
{
for (String s: vals)
// Here I can add s every string passed to an array list
The thing I'm wondering is: can I simply store all of the arguments passed to setArgs in an Array, instead of bothering with an ArrayList? I know arrays are immutable in java, so I was wondering if you can somehow there's an easy way to extract the arguments without using a loop.
Thanks.

Yes, Using Arrays class asList() method
List<String> argsList= new ArrayList<String>(Arrays.asList(vals));

Related

Why the Java lib stream() creates an array of objects when the element streamed is a splited string?

I have a string as follow "Aaaa Bbbb Cccc".
I want to turn this string into a list of strings and an array of string.
To make this possible, in first place I do the following action:
var list1 = Arrays.stream(input.split(" ")).toList(); System.out.println(list1);
Then, what appears is [Aaaa, Bbbb, Cccc].
Now it's the turn of the array.
When I print the class of the array, Java says it's has Object as its class (class [Ljava.lang.Object).
What can I do get a array of strings instead of Objects?
Not quite sure, if I got you right.
input.split(" ") already returns an array of strings. To create a List out of this array, you just have to use
Arrays.asList(input.split(" "))
An array in Java is internally also an object.
The reason for this output is that the toString() (which is used for output to println) method is implemented in the String class, but not in the Array object. Therefore, the standard toString() from the parent Object class is used. For similar output, you can use Arrays.toString().
If you have a String containing words separated by whitespaces like String str = "Aaaa Bbbb Cccc";, you can get a String array by using just the split method: String[] arr = str.split(" ");. Then you can get a List by using List<String> list = Arrays.asList(arr);.
However, if I understand your question correctly, you're asking why you're getting an Object array instead of a String array when using Arrays.stream(str.split(" ")).toArray(). Here, the reason is that the Arrays.stream() method has the following implementations: you can pass an int[], long[], or double[] array when the array contains primitive data types. You cannot pass any array of other primitive data types like char[] as an argument to Arrays.stream(). In your case, your array contains objects of the String type; however, the implementation of Array.stream() uses a generic data type T[] for any non-primitive types. An unbound generic array resolves to the type Object[] at runtime and cannot easily be converted to any other type like String[]. Hence, you get the output that your array is of type Object[] rather than type String[].
So, if you have your variable str containing the words and you call System.out.println(str.split(" "));, you will get: [Ljava.lang.String. But if you call System.out.println(Arrays.stream(str.split(" ")).toArray());, you will get: [Ljava.lang.Object.
If you want to print the elements of the array in a readable form, you can use the Arrays.toString() method: System.out.println(Arrays.toString(str.split(" ")));. This will print [Aaaa, Bbbb, Cccc] to the console.
For the different variants of the Arrays.stream() method, see the documentation: Arrays (Java Platform SE 8)
If you want to better understand arrays of a generic type, see this resource on baeldung.com: Creating a Generic Array in Java

Input stored in Arraylist or String array? (New programmer) Java

It seems to me like ArrayList would be easier to use in nearly every scenario, it being very versatile. Is there an instance where a String[] would be used to store inputted data? If there is such a case, there must be a drawback in ArrayList, what would that be?
Only thing that comes to mind off the top of my head would be the variety of String methods like, substring() and split(), etc.
EDIT: New to StackOverflow as well. I apologize if this was a re-post. And thanks for the formatting.
The short answer is: don't use an array, always use an array list. The only exception to this is if you absolutely need to control the amount of memory used or you have some specific performance constraint that only String[] can support.
In general, though, arrays are terrible to work with in an object oriented language, and almost always for the same reason: they make it very easy to break encapsulation. For example:
public class ExampleArray {
private final String[] strings;
public ExampleArray(String... strings) { this.strings = strings; }
public String[] getStrings() { return strings; }
}
See any problems? Yea, you need to write getStrings() like this:
// ...
public String[] getStrings() { return Arrays.copy(strings); }
// ...
Otherwise, some caller can get a hold of your class' internal data and start modifying it. The only way to prevent this is to copy it every time a caller wants to see it. As opposed to the right way:
public class ExampleList {
private final List<String> strings;
// ...
public List<String> getStrings() { return Collections.unmodifiableList(strings); }
}
Now you're not copying the data, you're just sticking it behind an API that doesn't allow changes. If you use the Guava Immutable* classes, even better.
Of course there are situations where you want to use String[] instead. If you know in advance how long the list will be, for instance, and the list might be large.
The main disadvantage of using ArrayList is that as the list grows, the array has to be reallocated, which isn't a free operation. You can mitigate that by preallocating it to be the size (or larger) you expect using the constructor that accepts an initialCapacity.
ArrayList is dynamic grow-able array in size, Where as string array or any type of array is static in size.
Obviously this dynamic grow features cause some cost, it reallocate the array with new size and copy element to it.
You can initialize Java arrays at compile time, like:
String data[] = { "a", "b", "c" };
In old versions of Java there was also the case for type safety. ArrayList elements had to be casted to the original type whereas Java arrays where type safe.
Java arrays are part of the language and you will not be able to change them. ArrayList is part of the Java API. If you need (I do not recommend it though) you could substitute your own library to implement the ArrayList job.
Check out these questions asked by others in stackoverflow:
Array or List in Java. Which is faster?
Java Performance - ArrayLists versus Arrays for lots of fast reads
The only case that comes to my mind when array is used to hold some values is when there's a method taking variable number of arguments like:
void doSth(int i, String... strings){
if(strings.length>0){
//some stuff
}
Otherwise I hardly ever intentionally create a situation, when array needs to be used.

Difference between Arrays and 3 dots (Varargs) in java

Need to figure out what is the difference between ... and arrays in JAVA, also an array list.
It seems we can use both as unlimited, but ... is rarely used.
Really appreciate any help you can.
The three dots can only be used in a method argument, and are called 'varargs'. It means you can pass in an array of parameters without explicitly creating the array.
private void method(String[] args) {} is called like method(new String[]{"first", "second"});
private void method(String... args) {} is called like method("first", "second");
An array is a fixed length collection of objects. e.g. new int[5];
An ArrayList is a variable length collection of objects. e.g. new ArrayList<Integer>();
The ... in variadic functions is a part of a method signature denoting an array of parameters. e.g. public void printLines(String... lines)
In other words, method(String...) means passing a variable number of parameters to the method.

Meaning of int... or N... in java

I have a function from a library whose signature says:-
public void setColumnNames(N... columnNames);
1.) What is the meaning of 'N...' ?
Also I have a list like this:-
List<HColumn<String,String>>
I want to extract the 1st String of each element HColumn of this list and pass all these Strings as a single argument in above function. I am doing this job to compute the things that need to be displayed on a page of a website. Thus I need a superfast method to do so.
2.) How do I go for it ??
public void setColumnNames(N... columnNames)
means that setColumnNames takes any number of arguments of type N.
This feature is called varargs.
Taking glowcoder's suggestion, here's the other part:
2) Build an array of type N[] with the same length as the list, transfer the strings from the list to the array (converting them from String to N, however that's done), and pass the array as the argument to the function.

Java and setting a variable equal to an array

How do you set a variable equal to an array in Java. For example I have a class for input and a class for calculations which hold arrays. when I accept the user input from the input class how do I pass that variable into the array of my calculation class?
You should look into varargs. Code sample below:
public MyClass method(String ...arg);
You can call this method as :
method("test1", "test2", "test3"); // with arbitrary number of values.
Or as
String[] test = something;
method(test);
Unless you have strict requirements to use arrays, you should probably be using a Collection, like a List.
For example, if you're trying to manage an array of ints, you could instead do:
List<int> intList = new ArrayList<int>();
Then, if you really need the data in the form of an array, you can do:
intList.toArray();
Which would return an array holding the integer values in your list. Lists are easier to read and use.

Categories

Resources