I try to assign an array of numbers from 1 to 10 using the code below. Basically I am stuck on how to return an array. Do I need a toString method ?
package arrays1;
import java.util.Arrays;
public class Arrays1 {
/**
* #param args the command line arguments
*/
private int[] numbers;
private int DEFAULT_SIZE = 10;
public Arrays1(int size){
numbers = new int[DEFAULT_SIZE];
}
public int[] add(int[] n)
{
for(int i=0; i<numbers.length; i++){
numbers[i]=n[i];}
return numbers;
}
public int[] getValues(){
return numbers;
}
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
System.out.println(A.getValues());
}
}
How do I return contents of an array from this code? Do I need to create a new object?
A.getValues() is returning a pointer to the integer array numbers object, which is probably the output you're seeing. You don't need a new object, just use the one you made, Arrays1 A, and iterate over its contents, so something like this:
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
for (int i = 0; i < A.getValues().length; i++){
System.out.println(A.numbers[i]);
}
}
Yes, a toString method would be useful to serialize the contents of the numbers array to a String. But in this case, you should call it like this:
Arrays1 a = new Arrays1(9);
System.out.println(a); // it is an implicit call to toString()
Another acceptable alternative is to let the serialization to the client's responsibility. In this case, the client should rely on the getValues() method, and serialize it by itself:
Arrays1 a = new Arrays1(9);
System.out.println(Arrays.toString(a.getValues()));
Another lesser detail: Review your constructor: It does not use the parameter size, and that can be confusing.
Related
I would like following effect -> I have object of class FluidArray which will be an array, but depending on the input it will be either int array or String array:
FluidArray XXX = new FluidArray;
XXX.YYY[] might be either String or int
In this case variable YYY of class XXX might be int array or String
Can I somehow declare variable type depending on some choice?
public class FluidArray
{
VarType YYY;
public static void FluidArray(int a)
{
double[] YYY = new double[15];
}
public static void FluidArray(String a)
{
String[] YYY = new String[15];
}
}
Let's say I want to make a sort method.
I input there unsorted array.
I take out sorted array.
The catch is I might want to sort String, double or int array and I don't want to write 3 sorting methods - I thought that my sorting method might work on some defined object and this object will be either String, double int depending on my choice.
I am trying to use Generic type, I got so far sth. like this:
public class test
{
public static void main(String[] args)
{
FluidArray<Integer> arrTest = new FluidArray<>();
arrTest.arr[1]=2;
arrTest.arr[2]=3;
arrTest.arr[3]=4;
}
public static class FluidArray<arrType>
{
public arrType[] arr = (arrType[])new Object[15];
}
}
I don't understand, why I can't get access to the array, compiler ends when inserting first value.
Read up on Generics. Thats what they are supposed to do
For an assignment, I'm having to resize an array within a class, and due to the classes nature, it is easier to just create a new object of the class and then reassign itself?
Let me try and explain with code
public class foo {
// String Array instance
private String[] array;
// Constructor with a String array as a variable to initialize it's instance
public foo(String[] array){
this.array = array;
}
public void reassign() {
String[] differentArray = {};
foo temp = new foo(differentArray);
// Now here is where my problem lies
this = temp;
// out of this I get the following error
// The left-hand side of an assignment must be a variable
}
}
// Let also just say that for the sake of argument, I can't reassign
// 'array' to 'differentArray'
So, how would we make this work? Do I just have to hard code around it or is there a better way to change the reference to the object itself?
Any Advice would be appriciated
You can either mutate the class by reassigning the internal array: instead of String[] differentArray = {}; do array = {};. That will lose the previously stored information.
Or you can return a new foo object:
public Foo reassign() {
Foo temp = new Foo(...);
return temp;
}
Which is appropriate depends on what you are trying to achieve.
Proceed this way:
Foo.java
public class Foo{
// String Array instance
public String[] array; // I made this variable 'public' so that it would be accessible to the main method's class
// Constructor with a String array as a variable to initialize it's instance
public Foo(String[] array){
this.array = array;
}
public void reassign(int length) {
array = new String[length];
array[0] = "Hello"; // String to display in the main() method
}
}
App.java
public class App {
public static void main(String[] args) throws Exception{
String[] tab = new String[1];
tab[0] = "TempValue";
Foo myArray = new Foo(tab);
myArray.reassign(2); // new array with size = 2
System.out.println(myArray.array[0]);
myArray.array[1] = "World";
System.out.println(myArray.array[1]);
}
}
This prints :
Hello
World
to the console. Which proves that the reassign method worked.
I have been having issues with a class named arrayList that represents a list of objects and supports random access to its objects via a numeric position index.
The toString method should build and return a string containing the string representations of the objects currently accessible in the array, and when the logical size is 0; the string is empty.
I use a tester class to call the arrayList class.
public class Tester {
public static void main(String [] args) {
arrayList a1, a2;
a1 = new arrayList();
a2 = new arrayList(5);
a2.size();
System.out.println(a1.toString());
//System.out.println(a2.toString());
}
}
public class arrayList {
private int logicalSize;
private static Object[] array = new Object[0];
private Object[] original;
private Object removedElement;
public arrayList() {
Object[] array = new Object[]{null,null,null,null,null};
}
public arrayList(int i) {
logicalSize = i;
Object[] array = new Object[logicalSize - 1];
}
public arrayList(Object[] array) {
logicalSize = array.length;
Object[] copyArray = array;
}
#Override
public String toString(Object[] array) {
String str = " ";
for(int a = 0; a < logicalSize; a++) {
str = str + array[a];
}
str = str + "\nSize: " + size();
return str;
}
public int size() {
int length = array.length;
return length;
}
}
When the above code is run, I get "arrayList#(memmorylocation)".
I am only using a single dimensional array (the others are for a later part) and have tried various methods to get it to print anything but the location, including removing the loop that should print out values from the toString, and just doing:
System.out.println(a1);
instead of:
System.out.println(a1.toString());
but no matter what I change I still print out its location, and not its value.
How do I print the value instead of the location? I am using the BlueJ IDE.
Because you call the default method toString instead of the one you defined.
System.out.println(a1.toString());
Your method is supposed to receive an array as argument :
public String toString(Object[] array)
so pass in an array, or correctly override the toString() method. Note that using the #Override annotation would have told you that you did not override the method, which would probably made you avoid this mis-understanding.
By the way, by convention java class should start with an uppercase. So by convention, you should name your class ArrayList which already exists in java.util (as you probably know). You should change the name of your class for something more appropriate.
This syntax is repugnant :
Object[] array = new Object[]{null,null,null,null,null};
You want to do instead :
Object[] array = new Object[5];
I tried to make a parameter for an array for a method, but it always comes up with an error.
public void methodExample1() {
int array1[] = new int[4]
}
public void methodExample(Array array1[]) {
System.out.println(array1[0]);
}
But it always says there's an error in my parameter. Is there any way to do this?
Try this:
public void methodExample(int[] array1)
Explanation: The type is the same that you used for declaring a value that will be passed as parameter (for the moment I'm ignoring covariant arrays), for instance if you do this:
int[] array1 = new int[4];
... Then, at the time of passing it as a parameter we'll write it like this:
methodExample(array1)
Also notice that the size of the array must not be passed as parameter, and that by convention the [] part goes right after the type of the array's elements (in fact, int[] is the type of the array), and not after the array's name.
If I understand your question, then you could use Array, and something like
public static void methodExample(Object array1) {
int len = Array.getLength(array1);
for (int i = 0; i < len; i++) {
System.out.printf("array1[%d] = %d%n", i, Array.get(array1, i));
}
}
public static void main(String[] args) {
methodExample(new int[] { 1, 2, 3 });
}
Output is
array1[0] = 1
array1[1] = 2
array1[2] = 3
I assume that you are trying to pass array as a parameter to a method , to initialize it and then call another method to print it?
In java you have to create an object and "allocate" memory space for it by calling to new ...
so you can do like that :
public static void main(String[] args) {
int [] m_array; // creating a array reference
m_array = new int[5]; // allocate "memory" for each of of them or you can consider it as creating a primitive of int in each cell of the array
method(m_array); // passing by value to the method a reference for the array inside the method
}
public void method(int [] arr) // here you are passing a reference by value for the allocated array
{
System.out.println(arr[0]);
}
Hi guys i'm just starting to learn Java, and I wondering how can I access an array that was declared in a method from another method?
The design look like this:
public class Arrays{
int arraysize = 2;
public void initializeArray(){
float array[] = new float[arraySize]; // Declare array
}
public void accessArray(){
// I want to access the array from this method.
}
}
Read about scope of variables in java. This is link I could find on quick Google search. http://www.java-made-easy.com/variable-scope.html
You can declare the array at class level then it is accessible in all methods.
public class Arrays {
int arraysize = 2;
private float[] array = null;
public void initializeArray() {
array = new float[arraySize]; // Declare array
}
public void accessArray() {
// access array here.
}
}
Or You can pass the variables in method.
public class Arrays {
int arraysize = 2;
public void initializeArray() {
float[] array = new float[arraySize]; // Declare array
accessArray(array);
}
public void accessArray(float[] array) {
// access array here.
}
}
Given the amount of information, I have from question, approach 1 seems better than 2.
You need to move your declaration to make it a member, otherwise it will go out of scope once the initializeArray call ends. Then you can access the array from both methods. Try this:
public class Arrays{
float[] array;
int arraysize = 2;
public void initializeArray(){
array = new float[arraySize]; // Declare array
}
public void accessArray(){
array[0] = 1.0f;
}
}
This is done thusly
public class myClass{
int arraysize = 2;
float[] myArray; // Declare array
public myClass(){
myArray = new float[arraySize]; // initialize array
}
public float[] accessArray(){
return myArray;
}
}
The array declaration must not be done inside the class methods.
Variable declaration done inside a method limits it's scope of a variable to the method. (i.e you can't use it anywhere else).
The array is then instantiated in a constructor.
A constructor is a special function that is run when a class is instantiated.
Constructor are used to instantiated a class's variables
Constructors have the same name as their class and must not specify a return type (so no public int or public void just public)
Next you need to change the return type of the accessArray method. A return type of void states that the method isn't going to return anything. Change it to float[]
Then your accessArray method need only return the array variable.
EDIT: The
"return myArray;"
line of code gives a reference to the array to what ever called the function (Not a copy of the array, the actual array, a quick of Java is that it always does this except when returning primitive data types where it returns a copy)
If you want accessArray() to set floats in the array instead of returning the array it should be implmented like this.
public void accessArray(int index, float value){
myArray[index] = value;
}
There a two options:
You declare that array as instance variable
public class Arrays {
private int arraySize = 2;
private float array[];// Declare array
public void initializeArray() {
array = new float[arraySize];
}
public void accessArray() {
// I want to access the array from this method.
float first = array[0];
}
}
You pass the array as parameter to the method (resp. the initializeArray method should return an array)
public class Arrays {
public static void main(String[] args) {
int arraySize = 2;
float[] array = initializeArray(arraySize);
accessArray(array);
}
public static float[] initializeArray(int size) {
return new float[size];
}
public static void accessArray(float[] floats) {
// I want to access the array from this method.
float first = floats[0];
}
}