Hackermann
Hackermann

Reputation: 43

Java: Accessing an attribute in a class who also is an object of the same class

I'm studying as a beginner OOP in Java language, and found myself stuck when trying to do a specific task. Right now I'm trying to solve a problem where I have a class A that has 2 attributes, one is an object of same type A and a list with objects of type B, this type B only has one attribute and its an int.

Class B{
   int number;
}

Class A{
    A next;
    List<B> objects;    
{

Part of the problem that I'm having is "Make a method in class A that will return the object B with the lowest number in the current instance of the class A and its successors (A next). I'm not trying to find a code, but a way to be able to move between the current instance of the class that I'm at (Refering to Class A) and its forward references (A next). I'm making this question here because I haven't been able to find a question like this on my searches.

Upvotes: 0

Views: 760

Answers (1)

Gomathy M
Gomathy M

Reputation: 368

I have updated A class by following code

import java.util.*;
public class A {
    List<B> obj1;
    A next;
    A(A a,List<B> o){
        next = a;
        obj1 = o;
    }
    
    
    
    public void  lowestNumber()
    {
        List<B> objects = new ArrayList<B>();
        int i = obj1.get(0).number;
        System.out.println(" A next object size of list b is "+next.obj1.size());
        for(B ob: obj1)
        {
            if(ob.number < i)
            {
                i = ob.number;
                objects.add(ob);
            }
        }
        
        if(objects.size() != 0)
        {
            int j = objects.size() - 1;
            System.out.println(" B object lowest number is "+objects.get(j).number);
        }
        else {
            System.out.println(" B object lowest number is  "+objects.get(0).number);
        }
        
    }
}

and to execute this, for main method i have created seperate class C.java the following code is

import java.util.*;
public class C {
    public static void main(String[] args) 
    {
    List<B> y = new ArrayList<B>();
    List<B> u = new ArrayList<B>();
    
       
    
    B y1 = new B();
    y1.number = 3;
    B y2 = new B();
    y2.number = 4;
    B y3 = new B();
    y3.number = 1;
    B y4 = new B();
    y4.number = 2;
    y.add(y1);
    y.add(y2);
        y.add(y3);
        u.add(y4);
       u.add(y3);
        A n2 = new A(null, u);
        A n1 = new A(n2, y); 
        n1.lowestNumber();

    }
}

Output is

 A next object size of list b is 2
 B object lowest number is 1

Upvotes: 1

Related Questions