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
Related
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.
Very new to this. I'm trying to call a constructor method out of a separate class file that will make an array. Rather than post what I was working on for an assignment I've made a generic version that is much more simple.
What I am expecting is that the main will call MakeArray which will create an array of 3 integers: [0,1,2] then the main will add these terms and the only output would be the total, 2.
From my Main:
MakeArray trial = new MakeArray()
System.out.println(trial[0] + trial[1] + trial[2]);
From my class file:
final int CONSTANT = 3;
public MakeArray()
{
int[] demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
return demo[];
}
Thanks!
Creating an array like this won't work because arrays aren't normal objects but special ones.
So you can't just make an object that works the same as an array, instead make a static method (one that can be called without having an instance of a class) and make it return an array, like this:
static final int CONSTANT = 3;
public static int[] MakeArray()
{
int[] demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
return demo;
}
In that case you also have to make the constant variable static like I have done.
Then you can call this much like a constructor, you just need to add the name of the class it is placed in before it when you want to call it:
int[] trial = MakeArray.MakeArray();
This of course only works if you put this method in a class called "MakeArray" otherwise you have to put something else in front of the dot.
You don't appear to want a new instance of a MakeArray I suggest you make it an utility method.
From my Main:
int[] trial = MakeArray.newArray(3);
System.out.println(trial[0] + ", " + trial[1] + ", "+trial[2]);
with a utlity class defined as
enum MakeArray { ;
static int[] newArray(int n) {
int[] demo = new int[n];
for (int i = 0; i < n; i++)
demo[i]=i;
return demo;
}
}
You cannot access the MakeArray object as an array. You could however create a method returns said array:
class MakeArray {
public static int[] makeArray() {
int[] demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++) {
demo[i]=i;
}
return demo;
}
}
Then you can use it like that:
int[] trial = MakeArray.makeArray();
System.out.println(trial[0] + trial[1] + trial[2]);
One way to do it is to add an instance variable in your class and its corresponding getter method:
final int CONSTANT = 3;
int[] demo;
public MakeArray()
{
demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
}
public getArray(){
return demo;
}
Now you can call from main:
MakeArray arr = new MakeArray();
int[] trial = arr.getArray();
System.out.println(trial[0] + trial[1] + trial[2]);
As far I understand your question, you may be want something like this.
class file:
final int CONSTANT = 3;
public class MakeArray
{
public int[] demo;
public MakeArray()
{
demo = new int[CONSTANT];
for(int i=0; i<CONSTANT; i++)
{
demo[i]=i;
}
}
}
main class:
MakeArray trial = new MakeArray()
System.out.println(trial.demo[0] + trial.demo[1] + trial.demo[2]);
The ArrayList is initialised inside a Class and its values are set in a method (which are only existent in this method)
How could I prevent the arraylist from being empty or why is this even happening?
(Edit: I added this minor project to github (https://github.com/goodstuff20/NENAM))
List<Node> nodes = new ArrayList<Node>();
public Creature(Node[] nodes){
for(int i = 0; i < nodes.length; i++) {
this.nodes.add(nodes[i]);
}
System.out.println(this.nodes.size()); //4
}
public void tick(){
System.out.println(nodes.size()); //0
}
You have defined 2 contructors in class Creature. In the second ctor you make a call to the first using the new-operator:
public Creature(Node[] nodes){
//....
for(int i = 0; i < nodes.length; i++){
nodess.add(nodes[i]);
}
//....
}
public Creature(int[][] nodePos, int[][] musclePos){
//...
Node[] nodes = new Node[nodePos.length];
//...
new Creature(nodes);
}
Maybe your intention is to change the currently created object by calling the other ctor, but instead you create a new object with no relation to the first.
To call another ctor inside a ctor on the same object you have to use this, but that must be done in the first line.
For example:
public Creature(int[][] nodePos, int[][] musclePos){
this(...);
}
For your purposes it is better to use an init-method:
public Creature(Node[] nodes){
init(nodes);
}
public Creature(int[][] nodePos, int[][] musclePos){
//...
Node[] nodes = new Node[nodePos.length]; //when defineing an int length = normal and not -1
//...
init(nodes);
}
private void init(Node[] nodes) {
//...
for(int i = 0; i < nodes.length; i++){
nodess.add(nodes[i]);
}
//...
}
I try to analyze runtime information with reflections. The class I try to analyze has a static array of type me.instrumentor.InstrumentStackElem and I want to access and copy it using reflections.
The code looks like this:
final Field stack = this.object.getClass().getDeclaredField("ise_array");
stack.setAccessible(true);
final Object arr = stack.get(null);
final InstrumentStackElem[] tmp = new InstrumentStackElem[Array.getLength(arr)];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = (InstrumentStackElem) Array.get(arr, i);
}
When I try to run it, I get java.lang.ClassCastException: me.instrumentor.InstrumentStackElem cannot be cast to me.instrumentor.InstrumentStackElem at the line in the for loop.
Can anyone help me?
If it's sufficient for you to work on raw objects, you can try this solution. It enables you to work with arbitrary types and further you don't have to worry about different class loaders. A properly implemented toString() would be helpful too, I guess.
import java.lang.reflect.Array;
import java.lang.reflect.Field;
public class Main {
#SuppressWarnings("unused")
private static Integer[] targetArray = new Integer[] { 0, 1, 2, 3, 4, 5 };
public static void main(String[] args) throws Exception {
Field arrayMember = Main.class.getDeclaredField("targetArray");
arrayMember.setAccessible(true);
Object array = arrayMember.get(null);
int length = Array.getLength(array);
// get class of array element
Class<? extends Object> elementType = array.getClass().getComponentType();
Object copy = Array.newInstance(elementType, length);
for (int i = 0; i < length; i++) {
Array.set(copy, i, Array.get(array, i));
}
// if you know the type, you can cast
if (Integer[].class.isInstance(copy)) {
System.out.println("Integer[].class.isInstance(copy) == true");
Integer[] copiedArray = Integer[].class.cast(copy);
for (Integer i : copiedArray)
System.out.println(i);
} else {
for (int i = 0; i < length; i++) {
System.out.println(Array.get(copy, i));
}
}
}
}
OUTPUT
Integer[].class.isInstance(copy) == true
0
1
2
3
4
5
I cannot seem to find the correct way to write an array of a class. In this form no errors are thrown on compiling, but I receive an error when I try to make use of the array / class. The array of classes is in a class named HashTable (I'm required to write my own for an assignment) and I am testing it with the code below:
theHashTable.insert("aa", "ab");
Here is the HashTable class:
Edit: As pointed out by Aniket, fileNames was not being initialized. I corrected this below but receive the same error.
private class HashTable {
private class Value {
ArrayList<String> fileNames;
String word;
Value() {
fileNames = new ArrayList<String>();
}
}
private int currentSize = 101;
private Value[] items;
private HashTable() {
items = new Value[currentSize];
for (int i = 0; i < currentSize; i++) items[i] = new Value();
}
private int hash(String in) {
int out = 0;
for (int i = 0; i < in.length(); i++) out += 37*out+in.charAt(i);
out %= currentSize;
if (out < 0) out += currentSize;
return out;
}
public void insert(String inW, String inF) {
int index = hash(inW);
index = 0;
if (items[index].word.length() == 0) {
items[index].word = inW;
items[index].fileNames.add(inF);
}
else if (items[index].word.compareTo(inW) == 0) items[index].fileNames.add(inF);
else System.out.println("Collision");
}
}
fileNames ArrayList in your Values class is never initialized. Write a constructor for Values and Initialize fileNames.
Declare fileNames in your inner class value with initialization(line 3 in your sample code) as:
ArrayList<String> fileNames = new ArrayList<String>();