kpinz
kpinz

Reputation: 3

Creating an ArrayList of another class's objects and manipulating them

I have to create a second class called MyFractions that can store an arbitrary number of Fraction class objects, using an ArrayList of Fractions.

It will then need to have a method that does the following:

  1. Create four objects (representing fraction values) and store them in the collection.
  2. Retrieve the first fraction from the list and store it in a local variable.
  3. Call different methods of retrieved fractions from the arraylist.

This is what I have so far:

public MyFractions()
{
    fractions = new ArrayList<>();
}

public void demo(String fractionname)
{
    Fraction obj1 = new Fraction(2,3);
    fractions.add(obj1);
    Fraction obj2 = new Fraction(1,3);
    fractions.add(obj2);
    Fraction obj3 = new Fraction(4,3);
    fractions.add(obj3);
    Fraction obj4 = new Fraction(6,1);
    fractions.add(obj4);

}

}

And here is the Fraction class:

public Fraction(long num, long den)   
{
   numerator=num;
   denominator=den;
}

public Fraction(long num) 
{
   numerator=num;
   denominator=1;
}


public long denominator() 
{
    return denominator;  
}

public void dividedBy(Fraction otherFraction)
{
    numerator=numerator*otherFraction.denominator;
    denominator=denominator*otherFraction.numerator;
}


public boolean  equals(long n) 
{
    return  numerator==n;
}

public boolean  equals(Fraction otherFraction) 
{
    return numerator==otherFraction.numerator && denominator==otherFraction.denominator;
}

public void negative() 
{
    numerator= -numerator;
}


public long    numerator() 
{
    return numerator;
}


public void inverse() 
{
    long temp=numerator;
    numerator=denominator;
    denominator=temp;
}

public boolean  isProper()
{
    return numerator<denominator;  
}

public void times(Fraction other) 
{
    numerator=numerator*other.numerator;
    denominator=denominator*other.denominator;
}


public double   toDouble() 
{
    return 1.0*numerator/denominator;
}

public String toString() 
{
    return numerator + "/" + denominator;
}


public boolean  isWholeNumber()
{
    return denominator==1;
}

}

I can't seem to figure out how to retrieve the items from the list. I tried using different iterations and nothing seems to work.

Upvotes: 0

Views: 139

Answers (2)

Jam
Jam

Reputation: 642

You can use ArrayList.get(). If your task is to retrieve the first object and store it in a local variable you should do the following.

Fraction fraction1 = fractions.get(0);

If your final goal is to retrieve each one of them, then you should iterate though the Arraylist

Upvotes: 0

Jameson
Jameson

Reputation: 6659

To retrieve an item from a list, use ArrayList.get().

Or you can iterate over the collection:

for (final Fraction fraction : fractions) {
    System.out.println(fraciton.toString());
}

Or call whatever method you want to, if not toString().

Upvotes: 1

Related Questions