DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling

Trending

  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  1. DZone
  2. Coding
  3. Java
  4. Creating a Custom List With Java Implementing Iterator.

Creating a Custom List With Java Implementing Iterator.

In this post, we are going to talk about developing a custom data structure and how to create a list using Java.

By 
Juan Manuel Kelsy Romero user avatar
Juan Manuel Kelsy Romero
·
Updated Jul. 03, 19 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
32.6K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we are going to talk about developing a custom data structure and how to create a list using Java.

Before we code, we need to understand a few concepts.

List: A list is a data structure which represents a collection or arrangement of data (nodes), and every node has the pointer to the next node, which means the nodes can't be accessed by the index. The below image shows a list with three elements (nodes), and the "First" and "Last" pointers to make possible the access to the list data. 

Linked List with three elements

Node: A node is a structure which represents each element in the list. A node has at least one pointer to the next element and a field that contains the specific information or data. In a list with one element the first and last pointer point to the same element.

A Node

Next, Prev, First, Last (Pointers):  These are pointers which allow access to the nodes in a list. 

Empty List: A list without elements, the "first" and "last" nodes are null.

Empty List

Let's Code

First the Node class:

package app;

public class Node <T> {
    private Node next;
    private Node prev;
    private T data;

  //getters and setters omited..  
}

In the Node class, the important thing to highlight is the use of generic <T> to pass the data type of the node and make the list reusable.

After that, we need implement the CustomList class: 

package app;

import java.util.Iterator;

public class CustomList<T> implements Iterable<Node> {
    private Node first;
    private Node last;

    public CustomList() {
        first = last = null;
    }

    public boolean isEmpty(){
        return first == null;
    }

    public void push(T data) {
        Node tempo = new Node();
        tempo.setData(data);
        tempo.setNext(null);

        if (first == null) {
            tempo.setPrev(null);
            first = last = tempo;
        } else {
            tempo.setPrev(last);
            last.setNext(tempo);
            last = tempo;
        }
    }

    @Override
    public Iterator<Node> iterator() {
        return new ListIterator(first);
    }
}

The CustomList class implements Iterable, which allows us to use "for" with the list.

In the next step, we will create our own implementation of ListIterator:

package app;

import java.util.Iterator;

public class ListIterator implements Iterator<Node> {
    private Node current;

    public ListIterator(Node first) {
        current = first;
    }

    @Override
    public boolean hasNext() {
        return current != null;
    }

    @Override
    public Node next() {
        Node tempo = current;
        current = current.getNext();
        return tempo;
    }    
}

It is necessary to pass the first node of the list in the constructor to access the contents of the list using the pointers (next, prev) depending on your needs. We must also overload the next() and hasNext() methods.

Finally, we use our class to store Person and Car:

package app;

public class App {
    public static void main(String[] args) throws Exception {

        CustomList<Person> list1 = new CustomList<>();

        list1.push(new Person("Clark", "Kent", 35));
        list1.push(new Person("Bruce", "Wayne", 40));
        list1.push(new Person("Linda", "Carter", 30));

        for (Node node : list1) {
            System.out.println(node.getData().toString());
        }

        CustomList<Car> list2 = new CustomList<>();
        list2.push(new Car(200, "Car 1"));
        list2.push(new Car(100, "Car 2"));

        for (Node node : list2) {
            System.out.println(node.getData().toString());
        }        
    }
}

In the above code, we noticed that we can iterate over the lists with the for structure.

That's all folks, we've implemented our custom List with Java by implementing Iterator.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!