Java: How to create an array object with a constructor? [duplicate] - java

This question already has answers here:
When do you use varargs in Java?
(8 answers)
Closed 4 years ago.
I could use help/direction on how to build a constructor that receives (for example 1, 2, 3) int's and stores them into an array object called arr2.
Part I:
public static void main (String[] args) {
Create an Arrays object using the first constructor
Arrays arr1 = new Arrays(5);
Arrays arr2 = new Arrays (1,2,3);
}
Part II:
public class Arrays {
private int [] array;
private int count;
public Arrays(int[] arr){
int[] array = arr;
array= arr;
count = arr.length;
}}

You could do it like this:
public class Arrays {
private int [] array;
public Arrays(int... arr){
array = arr.clone();
}
public int get(int index) {
return array[index];
}
}
Changes from your code:
The constructor uses varargs (look it up).
There is no need to store the count; if you want the count the count, use array.length().
The array is copied. This means you can change the original array that you passed in, but the values in the Arrays object won't be affected.
I've added a getter method.

Try use this constructor with var args
public Arrays(int... arr) {
int[] array = arr;
array= arr;
count = arr.length;
}

Related

initialize an empty array but failed to use in java

I hava a question about array initialization in java.
The code is as below:
public class Sentence {
int size;
int[] words=new int[size];
public Sentence(int size) {
this.size=size;
}
public static void main(String[] args) {
Sentence falseOne = new Sentence(6);
falseOne.words[0] = new int[6];
}
}
The problem shows: Type provided "int[]", but required "int"
Could anyone tell me where is wrong?
The field words for an object of class Sentence is of type int[] i.e. it is an array whose elements must be of integer type. In the second line within the main function, you are trying to initialize the first element of the words array with an integer array, instead of an integer.
Also, you should also create the array itself within the constructor.
The code should look like this:
public class Sentence {
int size;
int[] words;
public Sentence(int size) {
this.size = size;
this.words = new int[size];
}
public static void main(String[] args) {
Sentence falseOne = new Sentence(6);
falseOne.words[0] = 7; //just picked an arbitrary integer to demonstrate what should be initialized
}
}

how to reassign array variable stored in an object in java

I'm new to this site so let me know if this sort of question is welcome here.
I'm currently coding a class in java to store a set of integers in an array stored in an object and i'm having trouble reassigning the array variable store in the objects created. its not compiling as is(I'm a new programmer so i'm pretty sure i'm missing something simple here).
public class Set
{
// constructor
Set()
{
int array[] = {};
}
//adds a value to the set
public static void addValue(int [] array, int element)
{
int i;
int n = array.length;
int newArray[] = new int[n + 1];
//copy original array into new array
for (i = 0; i < n; i++)
newArray[i] = array[i];
//add element to the new array
newArray[n] = element;
//the issue is this line here
this.array = newArray;
}
//print the set
public static void printSet(int [] array)
{
int i;
int n = array.length;
System.out.print("{");
for (i = 0; i < n; i++)
{
System.out.print(array[i]);
}
System.out.println("}");
}
}
edit - error message returned is:
Set.java:23: error: non-static variable this cannot be referenced from a static context
this.array = newArray;
^
Set.java:23: error: cannot find symbol
this.array = newArray;
^
symbol: variable array
2 errors
First of all, you forgot to put the array inside the class, you can handle it privately like this before the constructor in this way:
private int [] array;
Constructor is used to initialize objects. If you create an empty constructor, you won't be able to pass it any parameters to initialize the array. You can create the constructor this way:
Set (int [] array){
this.array = array;
}
At line you indicated the compiler tells you that you cannot handle the method statically because you are working on an instance method. The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. So, you have to remove the static handling from the method. Also, since you want to return the array with the entered value, your method cannot be of type void. So, your method will be:
//adds a value to the set
public int [] addValue(int [] array, int element){
int newArray[] = new int[array.length + 1];
for (int i = 0; i < array.length; i++)
newArray[i] = array[i];
newArray[array.length] = element;
return newArray;
}
Since the length of the array was already available (array.length), it was not necessary to create the variable n, so I took the liberty of making some improvements to your code, to make it less redundant. Similarly, the method you created to print the array would be:
//print the set
public void printSet(int [] array){
System.out.print("{ ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println("} ");
}
However, once you've made these small changes your code should work fine. You can try to create a testing class like this, to check that everything works right:
public class TestingSet {
public static void main (String [] args){
//creating array
int [] array = {1, 2, 3};
//creating an instance of Set class
Set s = new Set(array);
//printing array
s.printSet(array);
//printing array with new value
s.printSet(s.addValue(array,4));
}
}
It looks like you are trying to access array however it cannot be seen by the addValue method.
You need to declare the array outside of the Set constructor:
public class Set
{
//New location to declear the array
int array[];
// constructor
Set()
{
//We can still initialize the array here
array[] = {};
}
Secondly, the reason for the error is that you cannot use this inside a static method. Static methods are not tied to an object (The Set class) so you need removed static from the method:
//static removed from this line
public void addValue(int [] array, int element)
{
Then to use the method you would create the Set object and use addValue something like this:
Set exampleSet = new Set();
exampleSet.addValue(yourArray, index);
The other option is to make the array a static value (it will no longer be specific to the object but shared with everything), but this is proberbly not the behaviour you want:
public class Set
{
//New location to declear the array
static int array[];
//And to access the object you could use
Set.array = newArray;

Why is array printed differently when it goes through other method that changes the array? [duplicate]

This question already has answers here:
Are arrays passed by value or passed by reference in Java? [duplicate]
(7 answers)
Closed 3 years ago.
The result you are suppose to get is 0, but I don't understand why? The array is changed when its passed through other method.
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
return arr[0];
}
public static int[] function2 (int [] arr) {
arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}
I expected 4 from the printed answer.
You are creating a completely new array in function2. That's why by default it is storing 0 at every index. When you are returning, the new array is returning only. For every index it will print 0 only.
Why are you creating new array in function 2? If you have to print 4 then simply pass the existing array only and print the arr[3].
Here is the code :-
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
//return arr[0];
return arr[3];
}
public static int[] function2 (int [] arr) {
//arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}

Converting Array of int to ArrayList and vice versa [duplicate]

This question already has answers here:
Convert an array of primitive longs into a List of Longs
(17 answers)
Closed 5 years ago.
I have an array int[] a = {1,2,3} I want to convert it to an ArrayList, and vice versa. These are my attempts but they don't work. Can someone point me in the right direction, please.
The following are my attempts below
public class ALToArray_ArrayToAL {
public static void main(String[] args) {
ALToArray_ArrayToAL obj = new ALToArray_ArrayToAL();
obj.populateALUsingArray();
}
public void populateArrayUsingAL()
{
ArrayList<Integer> al = new ArrayList<>();
al.add(1);al.add(2);al.add(3);al.add(4);
/* Don't want to do the following, is there a better way */
int[] a = new int[al.size()];
for(int i = 0;i<al.size();i++)
a[i] = al.get(i);
/* This does not work either */
int[] b = al.toArray(new int[al.size()]);
}
public void populateALUsingArray()
{
/* This does not work, and results in a compile time error */
int[] a = {1,2,3};
ArrayList<Integer> al = new ArrayList<>(Arrays.asList(a));
/* Does not work because I want an array of ints, not int[] */
int[] b = {4,5,6};
List list = new ArrayList(Arrays.asList(b));
for(int i = 0;i<list.size();i++)
System.out.print(list.get(i) + " ");
}
}
Accept the inevitability of a for loop:
for (int i : array) {
list.add(i);
}
...or use streams in Java 8, though frankly they're more of a pain than they're worth for this case:
Arrays.stream(array).boxed().collect(Collectors.toList())
...or use a third-party library like Guava and write
List<Integer> list = Ints.asList(array);

wrapper class(How to convert an array of primitives to an array of wrappers

Create a class WrapperDemo that includes a function convert2ObjAndStore that convertsan integer into an Integer object and stores the Integer object in a Vector object namedintVector.Store ā€œnā€ such converted objects in intVector.Iterate the vector and receive theobject as an integer value and display it.Also include a function that swaps one Integerobject with the other and display the swapped value in the calling routine (main function enclosed in a class named WrapperMain)
I tried this but i am getting an error for converting the interger to Integer object
import java.util.*;
class WrapperDemo {
static void Convert(Integer []ob,int n) {
Vector<Integer> store=new Vector<Integer>();
for(int i=0;i<n;i++) {
store.add(ob[i]);
System.out.println(store.get(i));
}
}
}
class WrapperMain {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
int[] x=new int [20];
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n);
}
}
}
As far as I can see your error is that you declare x as int[] but pass it to a method that is expecting Integer[]. This will not be autoboxed!
EDIT : To make it clearer ...
class WrapperDemo {
static void Convert(Integer []ob,int n) { // <-- type Integer[]
versus
int[] x=new int [20]; // <-- type int[] which is NOT equal to Integer[]
// and will NOT be autoboxed to Integer[]
// ...
WrapperDemo.Convert(x,n); // You give type int[] to a method that is expecting Integer[]
And as a side-note:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n); // <- You call the convertion in each iteration.
}
You call the convertion in each iteration of the filling loop. So most of the entries will be null. You might want to change that to:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
}
WrapperDemo.Convert(x,n);

Categories

Resources