Init array of object and pass values - java

I know there are plenty of question like this in the forum, but after searching for a good while I havent found the answer. I'm also very new to programming so dont flame me please.
I want to creat 8 objects off my class and pass different values to them.
f.e.
public class exampleClass(){
int value;
}
and then init them:
for(int i=0; i<7; i++){
exampleClass c= new // I get lost at this point
//and how can we pass "i" to the var "value" inside the new objects?
}
thanks a lot!

You need to give ExampleClass a constructor to populate the value. For example:
public class ExampleClass {
private final int counter;
public ExampleClass(int counter) {
this.counter = counter;
}
}
...
ExampleClass[] array = new ExampleClass[7];
for (int i = 0; i < array.length; i++) {
array[i] = new ExampleClass(i);
}

Related

How to call the constructor of the members of an array in Java?

I have a class:
public class a {
public int memberA;
private int memberB;
public a (int i) {
memberA = i;
memberB = ...;
}
}
and another one:
public class b {
public a[] = new a[10]; // <-- How do I call the constructor of 'a' with a value?
...
}
I tried many things, but nothing works! My app crashes if I don't call the constructor!
You can just use a for loop to instantiate each element of the array.
public class b {
public a[] arr = new a[10];
{
for(int i = 0; i < arr.length; i++) arr[i] = new a(/*some value*/);
}
}
As an aside, always follow Java naming conventions e.g. the name of the classes should be A and B instead of a and b. Better if you use self-descriptive names.

get an object based on its static value

I am initalizing several objects of the same type that have a common field:
public class Example {
private static objectCounter = 1;
public Example () {
objectCounter++;
}
}
Since these objects are created with a for loop like this
for (int i = 0; i<5; i++) {
Example e = new Example();
}
they are not referenced.
Is there a way to get a specific object based on objectCounter value ?
Something like
//get the Example object with objectCounter==2
get(2);
Thank you
My suggestion will be saving into array:
Example store[] = new Example[5]
for (int i = 0; i<5; i++) {
store[i] = new Example();
}
And then , search for the specific object.
As stated in the comments, a static value will persist through all instances of your class.
If you want your Example to "know" it's identity, pass it in when you construct it:
Example:
public class Example {
private int id;
public Example (int val) {
this.id = val;
}
// Getters/setters
}
Probably also want to add your objects to a list to access them later, so before your for-loop:
List<Example> examples = new ArrayList()<Example>;
And create them like this:
for (int i = 0; i<5; i++) {
Example e = new Example(i);
examples.add(e);
}

JUnit: test builder with private field

I'm a beginner and I have a problem with JUnit test in the constructor of a class.
The class that I want to test is called IntSortedArray and is as follows:
public class IntSortedArray {
private int[] elements;
private int size;
public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}
public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}
public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}
//other code...
}
With Eclipse I created a class for JUnit:
public class IntSortedArrayUnitTest {
private IntSortedArray isa;
#Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}
}
I started to write a test class with the intention to test all the methods of the class IntSortedArray, including constructors.
The first method testConstructorArray16Elements() wants to test the first builder.
So I thought I would check if the creation of the array elements is done properly, so the for loop counts how long elements and make sure it along 16 (as required).
But Eclipse generates (rightly) a mistake because elements is private.
How can I fix this error? I don't want to put the public field and if possible I would like to avoid creating a method public int[] getElements().
What do you recommend?
Another question: I can do two assert the same method? One to test the length of the array and the other to test that size is 0.
I hope not to have made big mistakes, this is the first time I use JUnit.
PS: how can I test the second constructor?
Thank you very much!
It looks like your class fields are declare as private but you trying to access then from outside the class. You need to provide the accessors methods in you class to make them visible:
private int[] elements;
private int size;
public static final int MAX = 16;
public int[] getElements() { ... }
public int getSize() { return size; }
Then you will be able to write below code:
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.getElements()) {
expected += 1;
}
assertEquals(expected, IntSortedArray.MAX );
It looks like your constructor has created an array for 16 integers, but does not initialize it with any value. To do that you should have below code:
public IntSortedArray() {
this.elements = new int[MAX];
this.size = 0;
for (int i=0 ; i < MAX ;i++) {
elements[i] = i;
size++;
}
}
You'll have to write a getter method for your array, or implement an Iterator

My test method is returning null when I run it

Apologies if the answer to this question is obvious! I've tried to initialize my field numbers with an array of numbers in a constructor in one class and then call it in my test class and display it as a string but it keeps returning null....any help would be appreciated!
This is my class that has the constructor:
public class NumerbList implements Number {
ArrayList<Number> numbers = new ArrayList<Number>();
//constructor taking array of type double as parameter
public NumberList(Double[] numberlist){
for(int i=0; i<numbers.size(); i++){
NumberDouble numberd = new NumberDouble(numberlist[i]);
numbers.add(numberd);
}
}
and the test class that creates an object of the NumberList class
public class Test {
public static void main(String[]args){
Double[] d = {2.4, 3.6, 4.3, 5.1};
NumberList numbers = new NumberList(d);
numbers.neg();
System.out.print(numbers.asString());
}
}
sorry neg is as follows :
public void neg(){
for(int i=0; i < numbers.size(); i++){
numbers.get(i).neg();
}
}
and asString is :
#Override
public String asString(){
return numbers.toString();
}
Should I put
for(int i=0; i < numberlist.length(); i++;)
in neg?
Thanks in advance!
The problem is that your for loop is using your initialize empty ArrayList as the size.
Change your loop to this:
for (int i = 0; i < numberlist.length; i++) {
// your loop logic here
}
Hope that helps!
for(int i=0; i<numbers.size(); i++){ should be for(int i=0; i<numberList.length; i++){
Also note that there is an easier (and generally preferred) way to iterate over your array:
for (Double number : numberlist) {
// your loop logic here
}
(I'd post that as a comment but it would lose the code formatting).

Copying an Object from Array to Array in Java

I'm trying to copy an Object I've created from one array to another of the same type in Java. When I run my program I receive a NullPointerException.
The relevant class functions are:
private int mState;
public Cell(int pRow, int pColumn, int pState) {
//other things
setState(pState);
}
public void setState(int pNewState) {
mState = pNewState;
}
public void setDead() {
mState = DEAD;
}
and the line in which the error occurs:
mFutureGeneration[i][j].setDead();
That array is defined as
private Cell [][] mFutureGeneration;
then dimensioned as
mFutureGeneration = new Cell[100][100];
It receives its contents from:
Cell [][] vSeedArray = new Cell[100][100];
which is filled as
for (int i = 0; i<100; i++) {
for (int j = 0; j<100; j++) {
int vNewState = mGenerator.nextInt(2) - 1;
vSeedArray[i][j] = new Cell(i,j,vNewState);
}
}
I think the problem is happening in the copy, but I was always under the impression Java copied by reference, so I can't see why it would be failing.
I copy the contents across with a loop
for(int i = 0; i<vSeedArray.length; i++) {
for(int j=0; j<vSeedArray[i].length; j++) {
mCurrentGeneration[i][j] = vSeedArray[i][j];
}
}
Any help would be appreciated.
Thanks.
I'm not sure you're ever allocating any "Cell" objects - just the array to hold them.
If so, that's probably the cause of your NullPointer exception.
Good link:
http://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm
Scroll down to the section "Array of Objects".
'Hope that helps!

Categories

Resources