Hey I'm trying to add pairs of numbers into an array by placing them into objects then putting the objects into the arrays but I seem to be having a problem with some part of my code. When I run the following example I just get the following back : [Example$Pair@1fc4bec, Example$Pair@dc8569, Example$Pair@1bab50a and so on...] can someone tell me why this is happening and how do I go about just printing the contents of the arraylist out correctly?

import java.util.*;

public class Example{

  ArrayList<Pair> ar1 = new ArrayList<Pair>();

  public static void main(String args[]){
    Example example = new Example();

    example.createArray();

  }

  public void createArray(){
    for(int i = 0; i < 5; i ++){
        ar1.add(new Pair(i, i+1));
    }

    System.out.println(ar1);
  }

  class Pair{
    int x = 0;
    int y = 0;

    public Pair(int a, int b){
        x = a;
        y = b;
    }

  }
}

Recommended Answers

All 10 Replies

Java is trying to print your Pair instances, which it does by calling their toString() method. All classes inherit one from Object, which just returns the name of the class and it's hash code, eg Example$Pair@1fc4bec
To print something more useful, override the public String toString() method to return something useful, eg x + ", " + y

commented: Correct and to the point. +13

I had a look around for the string override and came across an example of using getters to obtain the information. I've changed the print to :

for(Pair pair : ar1){
    System.out.println("no1: " + pair.getVal1() + ", No2: " + pair.getVal2());
} 

and changed the pair class to :

class Pair{
    int x = 0;
    int y = 0;

    public Pair(int a, int b){
        this.x = a;
        this.y = b;
    }

     public int getName(){
        return this.x;
    }

    public int getMarks(){
        return this.y;
    }

}

Is this the shortest/easiest way of doing it or will the string override be better?

public class Lecture implements Serializable {

public String title;
public String startTime;
public String endTime;
public String day;
public boolean classEnabled;

public Lecture(String title, String startTime, String endTime, String day, boolean enable){
    this.title = title;
    this.startTime = startTime;
    this.endTime = endTime;
    this.day = day;
    this.classEnabled = enable;
}

Next, you need to make a default constructor since serialization seems to require that. The last thing is you need to write your object out to a file. I usually use something like the following. Note this is for saving a game state so you might not want to use the cache directory.

note:(put a savestate)

final File cache_dir = this.getCacheDir(); 
final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);

FileOutputStream   fos  = null;
ObjectOutputStream oos  = null;
boolean            keep = true;

try {
    fos = new FileOutputStream(suspend_f);
    oos = new ObjectOutputStream(fos);

    oos.writeObject(this.gameState);
}
catch (Exception e) {
    keep = false;
    Log.e("MyAppName", "failed to suspend", e);
}
finally {
    try {
        if (oos != null)   oos.close();
        if (fos != null)   fos.close();
        if (keep == false) suspend_f.delete();
    }
    catch (Exception e) { /* do nothing */ }
}

Is this the shortest/easiest way of doing it or will the string override be better?

Overriding toString in Pair would be much easier. Then you could just print the list with System.out.println as you were trying to do before, and it would give you the result you expected.

I will need to be able to loop through the individual values soon though. I'm going to need to check every x value from each object in a loop, so toString wouldn't really help on that approach ?

No, not that requirement, but toString is always a useful thing to do.
For that requirement you would normally have a public int getX() method in the Point class, so you can call that for every Point in the loop.

Optional (ignore if you want): if you chose to make Point immutable by declaring x and y as final and setting them in the constructor then you can simply make them public and forget about accessor methods

ah okay then, I don't nessecarily need it for this project now but I will look into it if it's going to be useful for something else. I don't really understand how to access objects that I've stored in the array though. For example I need to be able to change the values of certain y values given the corresponding x value. So say I have an object in there (5, 23) and I want to change the y value of any object in the array with the x value of 5 to a 17 so it now be (5,17). I've got it searching the array and finding whether or not the x value exists, but not sure how to change the y value linked to it?

It's as easy as

for (int i = etc
   if (ar1[i].getX() == 5) ar1[i].setY(17);

I'm using the following code to go through the arraylist searching for the X value. I'm not sure how I'd use similar code to yours to acomplish it? I just get array required but arrayList found errors?

int location = 5;
int newY = 17;
for(Pair pair : ar1){
      int pairVal = pair.getValue();
      if(pair.getLocation() == location){
        //change the corresponding Y Value to the newY value


        break;
      }
    }

Managed to do it in the end using a for loop similar to yours ! Cheers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.