ADVERTISEMENT
ADVERTISEMENT

Java program to create a LinkedList collection of objects of a class

Java example to create a LinkedList collection of objects of a class.
Submitted by Nidhi, on April 23, 2022

Problem Solution:

In this program, we will create a Complex class and then create the list of objects of the Complex class using LinkedList collection. Then we will add and print complex numbers.

Program/Source Code:

The source code to create a LinkedList collection of objects of a class is given below. The given program is compiled and executed successfully.

// Java program to create a LinkedList collection 
// of objects of a class

import java.util.*;

class Complex {
  int real, img;

  Complex(int r, int i) {
    real = r;
    img = i;
  }
}
public class Main {
  public static void main(String[] args) {
    int i = 0;
    LinkedList < Complex > list = new LinkedList < Complex > ();

    list.add(new Complex(10, 20));
    list.add(new Complex(20, 30));
    list.add(new Complex(30, 40));
    list.add(new Complex(40, 50));

    System.out.println("List items: ");

    for (i = 0; i < 4; i++) {
      Complex C = list.poll();
      System.out.println(C.real + " + " + C.img + "i");
    }
  }
}

Output:

List items: 
10 + 20i
20 + 30i
30 + 40i
40 + 50i

Explanation:

In the above program, we imported the "java.util.LinkedList" package to use the LinkedList collection class. Here, we created two classes Complex and Main.

The complex class contains two data members real and img. And, created a constructor to initialize data members. The Main class contains a main() method. The main() method is the entry point for the program.

In the main() method, we created a list of objects of the Complex class using the LinkedList collection and added items using add() method. Then we printed complex numbers.

Java LinkedList Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.