Java and setting a variable equal to an array - java

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.

Related

What does new ClassName[0] do? (Java 8)

What does this syntax do, with square brackets around the number?
new Integer[0];
I've found it in a codebase I'm maintaining but I can't find any documentation on it. It is used like this:
Set<Form> forms = getForms();
List<Form> formsList = Arrays.asList(forms.toArray(new Form[0]))
It allocates an array with length zero; e.g. new Integer[0] creates a zero length array of Integer objects.
Why would you do that?
Well look at the javadocs for the form.toArray(T[]) method. Assuming that form is some subtype of Collection they are here.
The purpose of the toArray method is to copy the elements of the target collection (e.g. your form) into an array:
If the argument array is large enough to hold all elements, they are copied into that array. The result will be the argument array.
If the argument array is too small, a new array is allocated with the same type as the argument array and a length that is (just) enough to hold the elements. The elements are then copied into the new array, and it is returned as the result.
So what the code is actually doing is copying the elements of form to an Integer[] of the right size, and then wrapping the array to give a (fixed sized) List<Integer>. This can then be passed to some other code without worrying that that code might alter the original form collection.
Unlike traditional array which store values like string, integer, Boolean, etc. array of objects stores objects. The array elements store the location of reference variables of the object
Syntax:
Class obj[]= new Class[array_length]

Can we create an object without parentheses?

According to this site the syntax for creating a Java object is:
<JavaType> <variable> = new <JavaObject>();
Though you don't use any parantheses when creating an Array object and instead type brackets which contains the length of each dimension.
Example:
String[][] stringMatrix = new String[5][10];
What I am wondering is if this syntax is specifically and only for creating an Array object or I can make a custom class whose objects are created in a different way then usual
new <JavaObject>();
statement.
new keyword is used to allocate memory for the specific type, which is followed by new keyword.
MyClass obj = new MyClass();
Above line will create an object (allocate memory) for MyClass and initialize member variable by invoking default constructor.
But, below line of code will only allocate memory and initialize each element of array with default value null.
MyClass[][] objMatrix = new MyClass[5][10];
So, we are just declaring an array of size 5x10(allocating memory), but each element in array need some object reference (since, currently they have null reference). So, for that reason, you need to initialize each objMatrix array element by creating object of MyClass and assigning them to each element.
objMatrix[0][0] = new MyClass();
It is specifically for creating arrays. You're stuck with parentheses for your classes.
You can not create a custom class that changes the way the new operator works. However, there are some special cases where an object can be created without the usual new operator.
E.g.
String[] array = { "foo", "bar", "baz" };
Integer value = 42;
demonstrating that you can create arrays without the new keyword in a variable initializer, use String objects using literals and autobox primitive values to their object counterpart without the usual new syntax, but of course, this is not possible with custom types.
Another possibility to create objects without the new operator is deserializing them, which also works for custom types if they are Serializable.
Starting with Java 8, you can use constructor references if you have an appropriate context, e.g.
BigDecimal[] array = new BigDecimal[20];
Arrays.setAll(array, BigDecimal::new);
System.out.println(Arrays.toString(array));
Here, BigDecimal::new is a reference to a constructor of BigDecimal and it is implied from the context, i.e. Arrays.setAll that the function must be able to consume an int value, as the setAll method will evaluate it for every array element, passing the array index, so we initialize the array with ascending numbers in this example.
Another example would be
BigDecimal[] array = Stream.of("1.23", "4.56", "7.89")
.map(BigDecimal::new)
.toArray(BigDecimal[]::new);
System.out.println(Arrays.toString(array));
where it is implied from the context that the constructor used in the .map(BigDecimal::new) step must consume a String, as it will be evaluated for every stream element, ending up at a different constructor than in the first example.
BigDecimal is an ordinary class and these examples would work with a custom class as well, if it has matching constructors.

Storing string arguments array in a list :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));

Difference in containsAll behavior for Integer and int arrays (Java)

Could someone possibly explain why the following:
Integer[] arr1 = {1,2,3,4,5};
Collection<?> numbers = Arrays.asList(new Integer[]{1,2,3});
System.out.println(Arrays.asList(arr1).containsAll(numbers));
print "true", while if we exchange Integer for int like so:
int[] arr2 = {1,2,3,4,5};
Collection<?> numbers2 = Arrays.asList(new int[]{1,2,3});
System.out.println(Arrays.asList(arr2).containsAll(numbers2));
"false" is printed?
In the second case, each list consists of a single element. The two elements are both int[] arrays. The list containing the larger array does not contain the member of the list containing the smaller array.
The Arrays.asList() method accepts a variable argument list of arguments of type T, and returns a List<T>. With an array of Integers, T can be Integer, and the return type List. But with a primitive array, T cannot be an int, because there cannot be a List<int>.
List is a collection of objects and it works great if you put objects in it. As you are trying to create a list using primitive array, JVM is kind enough not to throw an exception but it is not able to create the list as you desired. And hence you see a difference in outputs when you you create a list with Integer array, which is valid and when you create a list with int array which is syntactically correct but logically against the principle of Collections.
according to this: What is the difference between an int and an Integer in Java and C#?
Integer is an Object and int is a primitive tho they are not directly the same...
So in the Java docs the Collection.containsAll(Object o) wants a Object and not a primitive.
Maybe this explains the different
http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#contains(java.lang.Object)
Didn't know this myself before thanks a lot for your Question.

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.

Categories

Resources