I'm very new to Java programming and wanted to try my hand at a little bit outside of my classes. I've created a class that will manipulate arrays, so I set up a private array with no size allocated to it. In a public constructor, how do I set the size of this array?
public ClassName()
{
arr = new int[10];
}
Remember that the Constructor is the method called when an object is instantiated. The Constructor must be a method with no return type and the same name as the class. You could even take in parameters if you'd like to(say a size variable), then create a new array based on the size.
For instance, you could do this:
public ClassName(int size)
{
arr = new int[size];
}
Now when in your tester class, you could create a new object using that constructor.
ClassName c = new ClassName(5);
Which creates a new object with an array of size 5 as a class variable. Hope this helped!
Edit: I should add; if you do not specify a constructor, Java will do it for you, but it will do nothing.
Just like in must of the languages.
example:
anArray = new int[10]; //10 - array size, int is the array type
read about JAVA Arrays
Related
I'm a Java beginner and I don't understand how to make it. When I write in my code something like in the example, my IDE underlines it and says it's wrong when I only started writing my code. Can anybody help me guys?
Example:
public class ArrayUtils {
public static int[] lookFor(int[] array) {
int[] array = {};
}
}
The variable named array is already passed in as a parameter. Which means that you cannot create a new int[] named array inside the java method. Try naming it something else.
Syntax with {} means initialization of your array like int[] array = {1,2,3}.
But you can't initialize the variable with the same name as parameter's name.
You can assign a new array to the variable:
public static int[] lookFor(int[] array) {
array = new int[6]; // assign to variable new array with length 6
array = new int[]{1,3,5}; // assign to variable new array with initialized values
}
Note: in first case all 6 values will be zero
Update: as it was mentioned by #ernest_k reassigning method parameters is a bad practice. To avoid it method parameter usually marked as final int[] lookFor(final int[] array)
I have declared a class named Member. I then assigned an array with Member type. When I try to put things into the array, it gives me this error:
Exception in thread "main" java.lang.NullPointerException
at HW2_2.main(HW2_2.java:15)
This is my code:
import c.Member;
import java.util.Scanner;
public class HW2_2
{
public static void main(String []args)
{
Member[] p = new Member[100];
Scanner in = new Scanner(System.in);
p[0].setID("apple12");
p[0].setPassword("1234");
p[0].setFirstname("fname");
p[0].setLastname("lname");
p[0].setEmail("*#gmail.com");
}
}
How do I fix this to the point where I can store data into my array?
You have created an object p which points to an array of Member objects. This is perfect. However, each object in your array is by default null. You cannot simply perform operations on them.
You probably want to do something like...
//...
p[0] = new Member(...);
p[0].setId("ID");
//... And so on
What's important to learn from here is that an array declaration syntax does not initialize the values of the array itself. That would be impossible, right? How would you pass arguments to the constructors of each one seperately? You have to do it manually.
When you:
Member[] p = new Member[100];
it initializes all array members to null (since this is an array of object types).
You need to initialize members if you want them to be usable, therefore here you have to:
p[0] = new Member();
before you can use that member.
If you want to initialize all members at once, you need to loop over all elements in the array and create one for each member; with Java 8 this can be done as such:
IntStream.range(0, p.length).forEach(index -> p[index] = new Member());
Curiously enough, there is no such method as <T> void fill(T[] array, Supplier<T> supplier) in the Arrays class.
So I have this class, and I want to method that takes in an int, and creates a new array of that size. If I
declare
newArray<Object<int,int>> array1 = new newArray<Object<int,int>>(10);
This would create an array of size 10.
I've tried doing
public class newArray<O>
{
private O[] array;
public newArray(int newArraySize)
{
newArray<O>[] = new newArray<O>[newArraySize];
}
}
but I get an " Cannot create a generic array of newArray " error.
Unfortunately, you can't create a generic array. This is due to the way generics are implemented in Java, which is through type erasure. In effect, all generic types are "erased" to their bounding type (usually Object) before compilation, so all the compiler sees are Object instead of T or E or O. The erasure process generates automatic casts to ensure that the program would still work as intended.
This means that you can't do:
new O() (this gets erased to new Object(), which the compiler has no idea what to do with)
new O[] (this gets erased to new Object(), which again isn't helpful to the compiler)
What you can do is casting:
array = (O[]) new Object[size];
And in fact, that's how it's done in Java's Collections framework. You'll get an "unchecked" warning, as the compiler can't prove that this conversion is safe, but there really is no other option.
Also, few things I want to point out about your question, that you may or may not know already:
You can't use primitives as type parameters
Object has no type parameters
newArray<O>[] = new newArray<O>[newArraySize]; should really be array = new newArray<O>[newArraySize];. You already declared the array you wanted to use. So use it!
Looks like you're implementing your own ArrayList, in fact. If you are, good luck! If you aren't, you should really be using the existing implementation, unless you need some special behavior that you can't get otherwise...
You are almost there.
Take a look at the following code for an example on how to initialize, populate, and print an array.
import java.util.*;
public class Test
{
public static void main(String[] args)
{
// define the array
List<Integer> array1 = new ArrayList<Integer>(10);
// initialize the array with some value. In this case, the Integer "200"
// note that the array doesn't have a hard limit of 10 as define above. You can change the following value to 20 and it will still work
for (int i = 0; i < 10; i++)
{
array1.add(i, 200);
}
// print the array
System.out.println(array1);
}
}
Does this help?
ArrayList<Integer[][]> r = new ArrayList<Integer[][]>(10);
// You could replace the above list with a custom list
Integer[][] ob = new Integer[1][2];
ob[0][0] = 10;
ob[0][1] = 20;
r.add(ob);
for(Integer[][] o : r)
for(Integer[] o1 : o)
for(Integer o2 : o1)
System.out.println(o2);
And the output is:
10
20
I am having a little trouble understanding the concept of final in Java.
I have a class that follows:
public class MyClass
{
private int[][] myArray; // intended to be changed
private final int[][] MYARRAY_ORIGINAL; // intended to be unchangable
public MyClass(int[][] array)
{
myArray = array;
MYARRAY_ORIGINAL = array;
}
}
I was under the understanding that final would make MYARRAY_ORIGINAL read only. But I have tried editing myArray, and it edits MYARRAY_ORIGINAL as well. My question is, in this context, what exactly does final do? And for extra credit, how can I copy the array passed through the constructor into MYARRAY_ORIGINAL so that I can have 2 arrays, one to edit, and one that will remain preserved?
Your final MYARRAY_ORIGINAL is indeed read only: you can't assign a new value to the MYARRAY_ORIGINAL reference in other side than class constructor or attribute declaration:
public void someMethod() {
//it won't compile
MYARRAY_ORIGINAL = new int[X][];
}
The values inside the array are not final. Those values can change anytime in the code.
public void anotherMethod() {
MYARRAY_ORIGINAL[0][0] = 25;
//later in the code...
MYARRAY_ORIGINAL[0][0] = 30; //it works!
}
If you indeed need a List of final elements, in other words, a List whose elements can't be modified, you can use Collections.unmodifiableList:
List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
The last piece of code was taken from here: Immutable array in Java
In case of Objects, final makes reference can't be changed, but object state can be changed.
That is the reason why you are able to change values of final MYARRAY_ORIGINAL
MYARRAY_ORIGINAL is indeed read only variable. Your array reference can not be assigned a new value nor for their length of the arrays can be changed. A final variables initialization can be deferred till the constructors is called. If one tries to modify the reference of the final variable, compiler will throw an error message. But what is possible is, one can edit the elements of the MYARRAY_ORIGINAL and of the myArray i.e one can change the state of the object assigned to a final variable. For example
Class A {
final int[] array;
public A() {
array = new int[10] // deferred initialization of a final variable
array[0] = 10;
}
public void method() {
array[0] = 3; // it is allowed
array = new int[20] // not allowed and compiler will throw an error
}
}
To understand more on final please take a look at Java Language Specification on final variable.
Final does not mean 'read-only' per se, but more so "safe publication' for other threads than the one to which it is defined. Another aim of 'final' is that it ensures the latest object available in a multi-thread environment.
Secondly, if you define something as "final", for example:
private final int[][] MYARRAY_ORIGINAL;
The reference is "final", but not the object itself. A much better way to understand it would be this:
public static final List myList = new ArrayList();
Now I can access myList from any other threads - I can modify it (add to it); but I cannot
(a) Declare it again - myList = new ArrayList();
(b) Assign it another list - myList = anotherList;
The context for final I would see best, in a multiple-thread scenario.
Bonus: to answer your question, you cannot make a 'readonly' array, you will have to manage that yourself (as final, only maintains 'read-only' to reference not object)
You can use the method System.arraycopy to make a copy of the array as follows -
int[][] source = {{1,2},{3,4}};
int[][] copy = new int[source.length][];
System.arraycopy(source, 0, copy, 0, source.length);
Also, you some problem with your code regarding what you are trying to do. If you look at the constructor
public MyClass(int[][] array) { //something else passes the array
myArray = array;
MYARRAY_ORIGINAL = array; // you are just keeping a reference to it can be modified from outside
}
If you really want nobody to modify the values in that array MYARRAY_ORIGINAL, you should make a copy of the source array that comes comes from outside.
public MyClass(int[][] array) {
myArray = array; //make a copy here also if you don't want to edit the argument array
MYARRAY_ORIGINAL = new int[array.length][];
System.arraycopy(array, 0, MYARRAY_ORIGINAL, 0, array.length);
}
Now you shouldn't have to worry about the array's being modified from outside.
I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.