All my objects change in my arraylist - java

I'm adding a new object(class) to an ArrayList, but when I try to get variables from the objects in my ArrayList, the variables are the same in all my classes. I've added a NEW object, so I expect it to add a new object, right?
This is my code in my for loop. The print says that every variable in the object[i] has the same number.
ArrayList treeDots;
ArrayList branchList;
boolean clicked;
void setup ()
{
size(1024, 768, P3D);
clicked = false;
treeDots = new ArrayList();
branchList = new ArrayList();
treeDots.add(new TreeDot(width/2, height/2));
}
void draw ()
{
if (clicked)
AddTreeDot();
if (treeDots.size() > 1)
{
for (int i = 0; i < treeDots.size() -1 ; i++)
{
int temp_loc = 0;
TreeDot index1 = (TreeDot)treeDots.get(i);
TreeDot index2 = (TreeDot)treeDots.get(i + 1);
print(index1.xLoc(temp_loc) + " ");
print(i + " ");
print(index2.xLoc(temp_loc) + " ");
print(i + " ");
strokeWeight(2);
stroke(#09FF00);
line(index1.xLoc(temp_loc),index1.yLoc(temp_loc), index2.xLoc(temp_loc), index2.yLoc(temp_loc));
}
}
}
void AddTreeDot ()
{
int randomX = 0;
int randomY = 0;
treeDots.add(new TreeDot(randomDotX(randomX), randomDotY(randomY)));
clicked = false;
}
int randomDotX (int _randomX)
{
TreeDot temp = (TreeDot) treeDots.get(treeDots.size() -1);
int temp_x_loc = 0;
int lastDotX = temp.xLoc(temp_x_loc);
_randomX = lastDotX + int(random(-10, 10));
return _randomX;
}
int randomDotY (int _randomY)
{
TreeDot temp = (TreeDot) treeDots.get(treeDots.size() -1);
int temp_y_loc = 0;
int lastDotY = temp.yLoc(temp_y_loc);
_randomY = lastDotY + int(random(0, 10));
return _randomY;
}
void mouseClicked ()
{
clicked = true;
}
and here is my class code
int randomSpread;
boolean canIGrow;
boolean endDot;
int x_loc;
int y_loc;
int lineThickness;
class TreeDot
{
TreeDot (int x_loc_par, int y_loc_par)
{
x_loc = x_loc_par;
y_loc = y_loc_par;
//ellipse(x_loc_par, y_loc_par, 10, 10);
endDot = false;
}
int xLoc (int _x_loc)
{
_x_loc = x_loc;
return _x_loc;
}
int yLoc(int _y_loc)
{
_y_loc = y_loc;
return _y_loc;
}
}

The problem that you have to declare variable inside the class & this code will be prblematic.
int xLoc(int _x_loc)
{
_x_loc = x_loc;
return _x_loc;
}
int yLoc(int _y_loc)
{
_y_loc = y_loc;
return _y_loc;
}
Then in call it
int temp_loc = 0;
TreeDot index1 = (TreeDot)treeDots.get(i);
TreeDot index2 = (TreeDot)treeDots.get(i + 1);
print(index1.xLoc(temp_loc) + " ");
print(i + " ");
print(index2.xLoc(temp_loc) + " ");
print(i + " ");
This line index1.xLoc(temp_loc) reset the value for you to 0.

Your TreeDot getters/setters are messed up. In xLoc() you are passing in _x_loc, making it equal to x_loc and return it. Same for yLoc()

Class variables should be declared inside the class.
What you're doing is you're setting the same (global) variables each time you add a new TreeDot.
P.S. your getters are not the problem as some of the answers are mentioning.

Related

How to correctly implement maximum weight independent set of positive tree using BFS

can someone help me implement the maximum weight independent set for a TREE (not a graph)?
The tree is represented by an adjacency matrix, and we have an array for the weights of the vertices.
BFS output: // 0: distances from start vertex
// 1: BFS-order
// 2: parent-IDs
I tried this code, it doesn't work on all test cases and it says most of the time that the weight is too small.
Can someone help me find the errors?
import java.io.*;
import java.util.*;
public class Lab5
{
/**
* Problem: Find a maximum weight independent set using dynammic programming.
*/
private static int[] problem(Tree t, int[] weights)
{
// Implement me!
//base cases
if (t.noOfVertices==0) {
return new int[] {};
}
if (t.noOfVertices==1) {
return new int[] {weights[0]};
}
//we will implement this using bfs, we will use 0 as the root
int[][] bfs = t.bfs(0);
//finding leaves
int leaf[] = new int [t.noOfVertices];
//now we can implement our algorithm
//M is the maximum weight of the tree if it contains i, and M1 is the maximum weight of the tree if it doesn't contain i
int M[]=new int[t.noOfVertices];
int M1[]=new int[t.noOfVertices];
//treating elements that aren't leaves
int nodeDiscovered[] = new int[t.noOfVertices];
for (int i = 0; i<t.noOfVertices; i++) {
if (t.edges[i].length==1) {
leaf[i]=1;
M[i]=weights[i];
nodeDiscovered[i]=1;
M1[i]=0;
}
else {
leaf[i]=0;
nodeDiscovered[i]=0;
}
}
for (int i = 1; i<t.noOfVertices; i++) {
if (leaf[i]==1) {
int node = bfs[2][i];
if (nodeDiscovered[node]!=0) {
continue;
}
while (node>-1) {
int parent = bfs[2][node];
ArrayList<Integer> sibs = new ArrayList<Integer>();
if (parent!=-1) {
for (int j = 0; j<t.edges[parent].length; j++) {
if (t.edges[parent][j]!=bfs[2][parent]) {
sibs.add(t.edges[parent][j]);
}
}
}
else {
sibs.add(node);
}
for (int sib : sibs) {
if (nodeDiscovered[sib]!=0) {
continue;
}
M[sib]=weights[sib];
for (int k : t.edges[sib]) {
if(bfs[0][sib]==bfs[0][k]-1) {
M[sib]=M[sib]+M1[k];
M1[sib]+=(M[k]>M1[k])?M[k]:M1[k];
}
}
nodeDiscovered[sib]=1;
}
node = bfs[2][node];
}
}
}
//putting the answers in an arraylist
ArrayList<Integer> set = new ArrayList<Integer>();
if (M[0]>M1[0]) {
set.add(0);
}
for (int i = 1; i<t.noOfVertices; i++) {
if (!set.contains(bfs[2][i]) && M[i]>=M1[i] ) {
set.add(i);
}
}
System.out.println(set);
//putting the elements of the arraylist into an array of int
int[] set1 = new int[set.size()];
for (int i = 0; i<set.size(); i++) {
set1[i]=set.get(i);
}
return set1;
}
// ---------------------------------------------------------------------
// Do not change any of the code below!
// Do not change any of the code below!
/**
* Determines if a given set of vertices is an independent set for the given tree.
*/
private static boolean isIndSet(Tree t, int[] set)
{
if (set == null) return false;
boolean[] covered = new boolean[t.noOfVertices];
for (int i = 0; i < set.length; i++)
{
int vId = set[i];
int[] neighs = t.edges[vId];
if (covered[vId]) return false;
covered[vId] = true;
for (int j = 0; j < neighs.length; j++)
{
int nId = neighs[j];
covered[nId] = true;
}
}
return true;
}
private static final int LabNo = 5;
private static final String course = "CS 427";
private static final String quarter = "Fall 2021";
private static final Random rng = new Random(190817);
private static boolean testProblem(int[][] testCase)
{
int[] parents = testCase[0];
int[] weights = testCase[1];
Tree t = Tree.fromParents(parents);
int[] solution = maxIsWeight(t, weights);
int isWeight = solution[0];
int isSize = solution[1];
int[] answer = problem(t, weights.clone());
if (!isIndSet(t, answer))
{
System.out.println("Not an independent set.");
return false;
}
int ansWeight = 0;
for (int i = 0; i < answer.length; i++)
{
ansWeight += weights[answer[i]];
}
if (ansWeight < isWeight)
{
System.out.println("Weight too small.");
return false;
}
if (answer.length < isSize)
{
System.out.println("Set too small.");
return false;
}
return true;
}
private static int[] maxIsWeight(Tree t, int[] weigh)
{
int n = t.noOfVertices;
int[][] dfs = t.dfs(0);
int[] post = dfs[2];
int[] w = new int[n];
for (int i = 0; i < n; i++)
{
w[i] = weigh[i] * n + 1;
}
boolean[] isCandidate = new boolean[n];
for (int i = 0; i < n; i++)
{
int vId = post[i];
if (w[vId] <= 0) continue;
isCandidate[vId] = true;
int[] neighs = t.edges[vId];
for (int j = 0; j < neighs.length; j++)
{
int uId = neighs[j];
w[uId] = Math.max(w[uId] - w[vId], 0);
}
}
int isWeight = 0;
int isSize = 0;
for (int i = n - 1; i >= 0; i--)
{
int vId = post[i];
if (!isCandidate[vId]) continue;
isWeight += weigh[vId];
isSize++;
int[] neighs = t.edges[vId];
for (int j = 0; j < neighs.length; j++)
{
int uId = neighs[j];
isCandidate[uId] = false;
}
}
return new int[] { isWeight, isSize };
}
public static void main(String args[])
{
System.out.println(course + " -- " + quarter + " -- Lab " + LabNo);
int noOfTests = 300;
boolean passedAll = true;
System.out.println("-- -- -- -- --");
System.out.println(noOfTests + " random test cases.");
for (int i = 1; i <= noOfTests; i++)
{
boolean passed = false;
boolean exce = false;
try
{
int[][] testCase = createProblem(i);
passed = testProblem(testCase);
}
catch (Exception ex)
{
passed = false;
exce = true;
ex.printStackTrace();
}
if (!passed)
{
System.out.println("Test " + i + " failed!" + (exce ? " (Exception)" : ""));
passedAll = false;
//break;
}
}
if (passedAll)
{
System.out.println("All test passed.");
}
}
private static int[][] createProblem(int testNo)
{
int size = rng.nextInt(Math.min(testNo, 5000)) + 5;
// -- Generate tree. ---
int[] parents = new int[size];
parents[0] = -1;
for (int i = 1; i < parents.length; i++)
{
parents[i] = rng.nextInt(i);
}
// -- Generate weights. ---
int[] weights = new int[size];
for (int i = 0; i < weights.length; i++)
{
weights[i] = rng.nextInt(256);
}
return new int[][] { parents, weights };
}
}
I attached an image that contains the algorithm that I used.

How to not print whole index if given number not found in table

I got this script to find given number from table and print number and index.
I'm having problem with number that are not in the table. I should print "number is not found" etc. and I tried with else, but not working. Any suggestions what to do with this?
with it prints whole table index.
import java.util.Scanner;
public class EtsitynAlkionIndeksi {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int[] taulukko = new int[10];
taulukko[0] = 6;
taulukko[1] = 2;
taulukko[2] = 8;
taulukko[3] = 1;
taulukko[4] = 3;
taulukko[5] = 0;
taulukko[6] = 9;
taulukko[7] = 7;
System.out.print("Mitä etsitään? ");
int etsittava = Integer.valueOf(lukija.nextLine());
// Toteuta etsimistoiminnallisuus tänne
int indeksi = 0;
while (indeksi < taulukko.length) {
int arvo = taulukko[indeksi];
int eiLoydy = 0;
if (etsittava == arvo) {
System.out.println("Luku " + etsittava + " löytyy indeksistä " + indeksi + ".");
} else {
System.out.println("Ei löydy " + eiLoydy);
}
indeksi++;
}
}
}
Use break as follows:
import java.util.Scanner;
public class EtsitynAlkionIndeksi {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int[] taulukko = new int[10];
taulukko[0] = 6;
taulukko[1] = 2;
taulukko[2] = 8;
taulukko[3] = 1;
taulukko[4] = 3;
taulukko[5] = 0;
taulukko[6] = 9;
taulukko[7] = 7;
System.out.print("Mitä etsitään? ");
int etsittava = Integer.valueOf(lukija.nextLine());
// Toteuta etsimistoiminnallisuus tänne
int indeksi = 0;
while (indeksi < taulukko.length) {
int arvo = taulukko[indeksi];
if (etsittava == arvo) {
System.out.println("Luku " + etsittava + " löytyy indeksistä " + indeksi + ".");
break;
}
indeksi++;
}
if (indeksi == taulukko.length) {
System.out.println("Ei löydy ");
}
}
}
A sample run:
Mitä etsitään? 3
Luku 3 löytyy indeksistä 4.
The statement, break; forces the loop to terminate. Also, note that I have moved System.out.println("Ei löydy " + eiLoydy); outside the while loop with the condition, if (indeksi == taulukko.length) i.e. if the value of indeksi has reached a value equal to taulukko.length, it means that the loop has not been terminated prematurely concluding that the lookup value has not been found.

How can I save image name and coordinates into save.txt file

Can you tell me what is wrong with my filewriter? I want the name of the image and the image coordinates saved into the file save.txt. Is there something I am missing? Am I even on the right track? This is my second project. My first was to make an array that can store images.
else if (savePicture.isPointInElement(clickX, clickY)){ //start of save code
FileWriter fw = new FileWriter ("save.txt");
for (int i = 0; i < arrayhat.numElements; i++){
if (arrayhat.images[i].isShowing){
fw.write("hat" + arrayhat.images[i].getXCenter() + " " + arrayhat.images[i].getYCenter() + " ");
}
}
for (int i = 0; i < arrayblunt.numElements; i++){
if (arrayblunt.images[i].isShowing){
fw.write("blunt" + arrayblunt.images[i].getXCenter() + " " + arrayblunt.images[i].getYCenter() + " ");
}
}
for (int i = 0; i < arraydealwithit.numElements; i++){
if (arraydealwithit.images[i].isShowing){
fw.write("dealwithit" + arraydealwithit.images[i].getXCenter() + " " + arraydealwithit.images[i].getYCenter() + " ");
}
}
for (int i = 0; i < arrayweed.numElements; i++){
if (arrayweed.images[i].isShowing){
fw.write("weed" + arrayweed.images[i].getXCenter() + " " + arrayweed.images[i].getYCenter() + " ");
}
}
fw.close();
System.out.println("saved");
}
else if (loadPicture.isPointInElement(clickX, clickY)){//start of load code
Scanner sc = new Scanner (new File("save.txt"));
for (int i = 0; i < arrayhat.numElements; i++){
arrayhat.removeimage(arrayhat.images[i], grouphat);
}
for (int i = 0; i < arrayhat.numElements; i++){
arrayblunt.removeimage(arrayblunt.images[i], groupblunt);
}
for (int i = 0; i < arrayhat.numElements; i++){
arraydealwithit.removeimage(arraydealwithit.images[i], groupdealwithit);
}
for (int i = 0; i < arrayhat.numElements; i++){
arrayweed.removeimage(arrayweed.images[i], groupweed);
}
while (sc.hasNext()){
String word = sc.next();
int x = sc.nextInt();
int y = sc.nextInt();
switch(word){
case "hat":
arrayhat.addImage(x, y, grouphat);
break;
case "blunt":
arrayblunt.addImage(x, y, groupblunt);
break;
case "dealwithit":
arraydealwithit.addImage(x, y, groupdealwithit);
break;
case "weed":
arrayweed.addImage(x, y, groupweed);
break;
}
}
sc.close();
}
And this is my sticker class
public class sticker {
public EZImage[] images;
public int numElements = 0;
public String filename;
void arraysticker(EZImage image, String name, int x, int y){
image = EZ.addImage(name, x, y);
}
public void addImage(int X, int Y, EZGroup group) {
images[numElements] = EZ.addImage(filename, X, Y);
group.addElement(images[numElements]);
numElements++;
}
public sticker (int size, String file){
filename = file;
images = new EZImage[size];
}
public void removeimage(EZImage image, EZGroup group){
if (containsElement(image)){
group.removeElement(image);
EZ.removeEZElement(image);
image = null;
}
}
public boolean containsElement(EZImage element){
for(int i = 0; i < numElements; i++){
if (element == images[i]){
return true;
}
}
return false;
}
}
You're using regular java arrays.
They need to extend the Party class
In all seriousness, this block of code is beginning with an "else" keyword and might be skipped based on the prior logic: please show us the if condition your initial "else" block is paired with.

Fix NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
How could I get the program to output all the information? IT currently returns a NullPointException error. Thanks.
I am supposed to use the delete methods just as they are, I cannot change them, but I am sure there must be something I can do.
public class TestCandidate7
{
public static int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void printResults(Candidate[] election)
{
double percent;
System.out.println("Candidate Votes Received % of Total Votes");
for (int x = 0; x < election.length; x++)
{
percent = (double) (election[x].votes()) / getTotal(election) * 100;
System.out.printf("%-15s %10d %20.0f", election[x].getName(), election[x].votes(), percent);
System.out.println();
}
}
public static void deleteByLoc(Candidate[] election,
int location)
{
if ((location > 0) && (location < election.length))
{
//move items up in the array -
for(int index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void deleteByName(Candidate[] election,
String find)
{
int location = 0;
int index;
// find location of item you want to delete
for(index = 0; index < election.length; index++)
if ((election[index] != null) && (election[index].getName().equals(find)))
{
location = index;
break;
}
else if (election[index] == null)
{
location = -1;
break;
}
if ((index != election.length) && (location >= 0))
{ //move items up in the array
for(index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[10];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
election[5] = new Candidate("Mickey Jones", 3000);
election[6] = new Candidate("Rebecca Morgan", 2000);
election[7] = new Candidate("Kathleen Turner", 8000);
election[8] = new Candidate("Tory Parker", 500);
election[9] = new Candidate("Ashton Davis", 10000);
System.out.println("Original results:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByLoc(election, 6);
System.out.println("Deleted location 6:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByName(election, "Kathleen Turner");
System.out.println("Deleted Kathleen Turner:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
}
}
Candidate
public class Candidate
{
// instance variables
int numVotes;
String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}
When you "delete" array elements, after the shift you assign null to the most right element of the array.
In your getTotal() you traverse the entire array and retrieve the value of numVotes for each element. When you reach the null element you are getting the exception since null does not have any fields..

Java constructor and modify the object properties at runtime

Note: This is an assignment
Hi,
I have the following class/constructor.
import java.io.*;
class Set {
public int numberOfElements = 0;
public String[] setElements = new String[5];
public int maxNumberOfElements = 5;
// constructor for our Set class
public Set(int numberOfE, int setE, int maxNumberOfE) {
int numberOfElements = numberOfE;
String[] setElements = new String[setE];
int maxNumberOfElements = maxNumberOfE;
}
// Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :(
static String[] removeAt(int k, String[] arr) {
final int L = arr.length;
String[] ret = new String[L - 1];
System.arraycopy(arr, 0, ret, 0, k);
System.arraycopy(arr, k + 1, ret, k, L - k - 1);
return ret;
}
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i] != null && setElements[i].equals(element) ) {
return retval = i;
}
retval = -1;
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem == -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
}
}
int getLength() {
if ( setElements != null ) {
return setElements.length;
}
else {
return 0;
}
}
String[] emptySet() {
setElements = new String[0];
return setElements;
}
Boolean isFull() {
Boolean True = new Boolean(true);
Boolean False = new Boolean(false);
if ( setElements.length == maxNumberOfElements ){
return True;
} else { return False; }
}
Boolean isEmpty() {
Boolean True = new Boolean(true);
Boolean False = new Boolean(false);
if ( setElements.length == 0 ) {
return True;
} else { return False; }
}
void remove(String newValue) {
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(newValue) ) {
setElements = removeAt(i,setElements);
}
}
}
int isAMember(String element) {
int retval = -1;
for ( int i = 0; i < setElements.length; i++ ) {
if (setElements[i] != null && setElements[i].equals(element)) {
return retval = i;
}
}
return retval;
}
void printSet() {
for ( int i = 0; i < setElements.length; i++) {
System.out.println("Member elements on index: "+ i +" " + setElements[i]);
}
}
String[] getMember() {
String[] tempArray = new String[setElements.length];
for ( int i = 0; i < setElements.length; i++) {
if(setElements[i] != null) {
tempArray[i] = setElements[i];
}
}
return tempArray;
}
Set union(Set x, Set y) {
String[] newXtemparray = new String[x.getLength()];
String[] newYtemparray = new String[y.getLength()];
Set temp = new Set(1,20,20);
newXtemparray = x.getMember();
newYtemparray = x.getMember();
for(int i = 0; i < newXtemparray.length; i++) {
temp.add(newYtemparray[i]);
}
for(int j = 0; j < newYtemparray.length; j++) {
temp.add(newYtemparray[j]);
}
return temp;
}
}
// This is the SetDemo class that will make use of our Set class
class SetDemo {
public static void main(String[] args) {
//get input from keyboard
BufferedReader keyboard;
InputStreamReader reader;
String temp = "";
reader = new InputStreamReader(System.in);
keyboard = new BufferedReader(reader);
try
{
System.out.println("Enter string element to be added" );
temp = keyboard.readLine( );
System.out.println("You entered " + temp );
}
catch (IOException IOerr)
{
System.out.println("There was an error during input");
}
/*
**************************************************************************
* Test cases for our new created Set class.
*
**************************************************************************
*/
Set setA = new Set(1,10,10);
setA.add(temp);
setA.add("b");
setA.add("b");
setA.add("hello");
setA.add("world");
setA.add("six");
setA.add("seven");
setA.add("b");
int size = setA.getLength();
System.out.println("Set size is: " + size );
Boolean isempty = setA.isEmpty();
System.out.println("Set is empty? " + isempty );
int ismember = setA.isAMember("sixb");
System.out.println("Element six is member of setA? " + ismember );
Boolean output = setA.isFull();
System.out.println("Set is full? " + output );
setA.printSet();
int index = setA.findElement("world");
System.out.println("Element b located on index: " + index );
setA.remove("b");
setA.emptySet();
int resize = setA.getLength();
System.out.println("Set size is: " + resize );
setA.printSet();
Set setB = new Set(0,10,10);
Set SetA = setA.union(setB,setA);
SetA.printSet();
}
}
I have two question here, why I when I change the class property declaration to:
class Set {
public int numberOfElements;
public String[] setElements;
public int maxNumberOfElements;
// constructor for our Set class
public Set(int numberOfE, int setE, int maxNumberOfE) {
int numberOfElements = numberOfE;
String[] setElements = new String[setE];
int maxNumberOfElements = maxNumberOfE;
}
I got this error:
\
javaprojects>java SetDemo
Enter string element to be added
a
You entered a
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:30)
at Set.add(Set.java:43)
at SetDemo.main(Set.java:169)
Second, on the union method, why the result of SetA.printSet still printing null, isn't it getting back the return value from union method?
Thanks in advance for any explaination.
lupin
You're shadowing your instance variables in the constructor:
When you write:
public Set(int numberOfE, int setE, int maxNumberOfE) {
int numberOfElements = numberOfE;
String[] setElements = new String[setE];
int maxNumberOfElements = maxNumberOfE;
}
That creates three new variables all of which only last the duration of the constructor. It should be:
public Set(int numberOfE, int setE, int maxNumberOfE) {
this.numberOfElements = numberOfE;
this.setElements = new String[setE];
this.maxNumberOfElements = maxNumberOfE;
}
You can drop the this. in this second version, but I find it clearer (it also lets you reuse variable names).
Also, you don't need to do:
String[] newXtemparray = new String[x.getLength()];
String[] newYtemparray = new String[y.getLength()];
Set temp = new Set(1,20,20);
newXtemparray = x.getMember();
newYtemparray = x.getMember();
Just:
Set temp = new Set(1,20,20);
String[] newXtemparray = x.getMember();
String[] newYtemparray = y.getMember();
is fine (note you also had a typo for newYtemparray; it was x.getMember)
These are reference variables. Currently, you're initialize them each to point to a new array. Then immediately, you assign them to point to a different array. So you're needlessly allocating and destructing memory.
Maybe because you forget about hiding? You don't assign any values to class vars in constructor, you just create new objects, which are garbage collected after constructor ends. Look for "scopes" or "visibility" for further info.

Categories

Resources