Array of a class (Java) - java

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>();

Related

Class Designing in OOPS ( JAVA )

Is there any ways to remove totalPermutationCount() from the interface because the only purpose of the method is to get permutationCombination value from the concrete class, if there are more concrete class or more instance variable then interface will become clumps and large.
Is there any other best approach other than constructor to assign values to the instance variable, that the entire class depends on.
Refer to how I have used and please help me to get better.
Interface
interface Word {
void performPermutation();
int totalPermutationCount();
}
Interface Implementation
class WordImpl implements Word{
// "word" is to store the word from the user
private String word;
// "convert" is to convert the word into a char array to perform the logic
private char[] convert;
// "permutationCombination" is to find the total number of combination that is done
private int permutationCombination = 0;
// Constructor
public WordImpl(String wordCom){
setWord(wordCom);
}
//getter setter of word instance variable
public void setWord(String wordCom){
if(!wordCom.isEmpty() && wordCom.trim().length() > 0){
word = wordCom;
}else{
word = "Default";
}
convertToChar();
}
// convert the given word to char array
private void convertToChar(){
convert = new char[word.length()];
for(int i = 0 ; i < word.length() ; i++){
convert[i] = word.charAt(i);
}
}
public int totalPermutationCount(){
return permutationCombination;
}
// -------------------------------- Below is the Temporary Logic Ignore it ---------------------------------------------
private void performSwap(char[] list , int from, int to){
char temp;
temp = list[from];
list[from] = list[to];
list[to] = temp;
}
public void performPermutation(){
char[] list = convert.clone();
Set<String> listData = new HashSet<>();
System.out.println(convert);
for (int i = 0 ; i < word.length() ; i++){
for (int j = i + 1 , reverse = i - 1 ; j < word.length() || reverse >= 0 ; j++ , reverse--){
if(j < word.length()){
performSwap(list,i,j);
System.out.println(convertToString(list));
list = convert;
permutationCombination++;
}
if(reverse >= 0 && i != 0){
performSwap(list,i,reverse);
System.out.println(convertToString(list));
list = convert;
permutationCombination++;
}
}
}
}
// ----------------------------------------------------------------------------------------
private String convertToString(char[] list){
String value = "";
for(int i = 0 ; i < word.length() ; i++){
value = value + list[i];
}
return value;
}}
Main Class
public class MyClass {
public static void main(String args[]) {
Word wordImplReference = new WordImpl("home");
wordImplReference.performPermutation();
System.out.println(wordImplReference.totalPermutationCount());
}
}
Below can help you with your queries:
if you remove totalPermutationCount method from interface you will loose benefit of abstraction achieved from interface class. If you still need to do that then you will need to use WordImpl wordImplReference = new WordImpl("home"); in your main method.
Assigning through constructor will be better in this case. It can be set using Set method in your WordImpl class, but setWord method would be required to be added in Interface.

Initialize array of objects(which has an array) in Java

I am relatively new to java, and this is only the second time I have ever tried to design a program that has an array of class objects. I am having trouble because when I go into debug mode, it is showing me that the arrays are being built correctly. However, when I try to build a string or even print to the console, I am getting a null pointer exception.
I am trying to make an array of Slot class objects.
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
Slot[] s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
And the Slot class has its own array, block[], constructed by a value passed in through its constructor.
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
short block[] = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Later in the program I then try to print to the console or build a string and it always breaks when I try to use any element in the slot[] in the C class.
Have I instantiated and initialized my 2 different arrays correctly?
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
Try something like these instead
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Replace
short block[] = new short[byteSize];
with
block = new short[byteSize];
Always use a this operator to initialize in a constructor so that you may differentiate clearly between local variables and instance variables
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
this.block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}

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

2 separated objects are connected for some reason

This is my homework(assignment). I really hope someone can help me figure out what I did wrong.
When I tried to create an object of State
state = new State(tablesize, tb);
and then tried to make a copy
State st2 = new State(state);
and then tried to modify the data in state
state.placeNumber(1,1,3);
for some reason, the data in st2 is also changed.
Below is the code. I really hope someone can point out where my mistake is.
Thanks
public class State
{
private int arraysize;
private int lastfilledx;
private int lastfilledy;
private int table[][];
//constructor
public State()
{
}
public State(State s)
{
arraysize = s.getsize();
lastfilledx = s.lastindex_x();
lastfilledy = s.lastindex_y();
table = s.gettable();
}
public State(int size, int[][] tb)
{
arraysize = size;
table = new int[size][size];
//copy the initial table which is a 2d array
table = tb;
for (int i = 0 ; i < size; i++)
{
for(int j = 0 ; j < size ; j++)
{
if ( table[i][j] == 1)
{
lastfilledx = i;
lastfilledy =j;
break;
}
}
}
}
public void placeNumber(int i, int j, int nextvalue)
{
lastfilledx = i;
lastfilledy = j;
table[i][j] = nextvalue;
}
public void printoutput()
{
for (int i=0; i < arraysize; i++)
{
for (int j=0; j < arraysize; j++)
System.out.print(" " + table[i][j]);
System.out.println("");
}
System.out.println("last fill " + lastfilledx + " " + lastfilledy);
}
public int[][] gettable()
{
return table;
}
public int getsize()
{
return arraysize;
}
public int lastindex_x()
{
return lastfilledx;
}
public int lastindex_y()
{
return lastfilledy;
}
}
public class Dikuho extends State
{
private static State state;
public static void main(String[] args) {
int tablesize = 3;
int tb[][] = new int[tablesize][tablesize];
/*****HARDCODE the table data***/
for (int i=0; i < tablesize; i++)
for (int j=0; j < tablesize; j++)
tb[i][j] = 0;
//test case for 3x3
tb[2][2] = 1;
tb[0][0] = tablesize*tablesize;
tb[0][1] = 7;
tb[1][0] = 8;
tb[2][1] = 2;
//initialize the state
state = new State(tablesize, tb);
**//Here is where the problem is. I only change the data in state but the data in st2 is also changed. I'm not sure what happen here.**
State st2 = new State(state);
state.placeNumber(1,1,3);
st2.printoutput(); **//These both printout same output which is not correct**
state.printoutput();
}
}
Your copy constructor has made a shallow copy of table 2D array. Both the original object and the copy refer to the same original array, because you assign the array reference from the original to the new object. That's fine for the int values, because the values are copied. But that's not okay for objects, for which references to the obejct are copied.
Instead of just copying the reference to the array...
table = s.gettable();
You'll need to create a new, copied array:
table = new int[arraysize][arraysize];
// 2 nested for loops here to copy the contents
public int[][] gettable()
{
return table;
}
So, both of your state objects are referencing the same array. you need to create a new array for each instance.

Why is there an NullPointerException?

I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.

Categories

Resources