Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6938983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T12:33:40+00:00 2026-05-27T12:33:40+00:00

Anyone know where I can obtain generic sample code for using an adjacency list

  • 0

Anyone know where I can obtain generic sample code for using an adjacency list to represent an undirected graph?

The graph data would be from a .txt file: The nodes are specified on the first line, separated by spaces. The edges are specified on the following lines, each edge on a separate line.

Like this…

1 2 3 4 5 6 7 8 9

1 2

1 4

1 3

2 4

2 5

3 6

4 6

5 7

5 8

6 9

7 9

8 9

My .txt file isn’t connecting with the graph methods. I’m also getting the following NPE error:

Error: java.lang.NullPointerException

Creating an adjacency list & performing standard Graph ADT methods for the undirected graph.

//TON of imports up here (removed for now)

class Graph<V> implements GraphADT1 <V>{

// Map of adjacency lists for each node
private HashMap<Integer, LinkedList<Integer>> adj;
private ArrayList<V> vertices;
private HashMap<V, LinkedHashSet<V>> neighbors;
private HashMap<V, Set<V>> neighborsView; 
private int edgeCount; 


public Graph(int[] nodes) {

    vertices = new ArrayList<V>();
    neighbors = new HashMap<V, LinkedHashSet<V>>();
    neighborsView = new HashMap<V, Set<V>>();
    adj = new HashMap<Integer, LinkedList<Integer>>();

    for (int i = 0; i < nodes.length; ++i) {
        adj.put(i, new LinkedList<Integer>());
    }
}

//Add Vertex Method
public void addVertex(V vid)    {
    vertices.add(vid);
    LinkedHashSet<V> neighborV = new LinkedHashSet<V>();
    neighbors.put(vid, neighborV);
    neighborsView.put(vid, Collections.unmodifiableSet(neighborV));

}

// Removes Vertex Method
public void removeVertex(V vid) {
    if(vertices.remove(vid)) {
        LinkedHashSet<V> neighborV = neighbors.remove(vid);
        for(V uid : neighborV) {
            LinkedHashSet<V> neighborU = neighbors.get(uid);
            neighborU.remove(vid);
            --edgeCount;
        }
        neighborsView.remove(vid);

    } else {
        throw new NoSuchElementException("no such vertex");
    }
}

//Add Edge Method 
public void addEdge(V uid, V vid) {
    LinkedHashSet<V> neighborU = neighbors.get(uid);
    LinkedHashSet<V> neighborV = neighbors.get(vid);
    if(neighborU == null) throw new NoSuchElementException("first argument not in graph");
    if(neighborV == null) throw new NoSuchElementException("second argument not in graph");
    if(neighborU.add(vid) && neighborV.add(uid)) {
        ++edgeCount;
    }
}

//Remove Edge Method
public void removeEdge(V uid, V vid) {
    LinkedHashSet<V> neighborU = neighbors.get(uid);
    LinkedHashSet<V> neighborV = neighbors.get(vid);
    if(neighborU == null) throw new NoSuchElementException("first argument not in graph");
    if(neighborV == null) throw new NoSuchElementException("second argument not in graph");
    if(neighborU.remove(vid) && neighborV.remove(uid)) {
        --edgeCount;
    } else {
        throw new NoSuchElementException("no edge between vertices");
    }
}



public void addNeighbor(int neighborV, int neighborU) {
    adj.get(neighborV).add(neighborU);
}

public List<Integer> getNeighbors(int v) {
    return adj.get(v);
}

public static void main(String[] args) {
    try {

        File file = new File("data.txt");
        InputStreamReader streamReader = new InputStreamReader(
                new FileInputStream(file));
        BufferedReader br = new BufferedReader(streamReader);
        String line = br.readLine();

        if (line != null) {

            // read nodes
            String[] nodeNames = line.split(" ");
            int[] nodes = new int[nodeNames.length];
            for (int i = 0; i < nodes.length; ++i) {
                nodes[i] = Integer.parseInt(nodeNames[i]);
            }

            // create graph
                Graph V = new Graph(nodes);


            // read edges
            while ((line = br.readLine()) != null) {
                String[] tokens = line.split(" ");
                int neighborV = Integer.parseInt(tokens[0]);
                int neighborU = Integer.parseInt(tokens[1]);

                // we add neighbor to each node in both directions.
                V.addNeighbor(neighborV, neighborU);
                V.addNeighbor(neighborU, neighborV);
            }

        }
        br.close();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
}




public Iterator<?> iteratorBFS(Object startVertex) {

    return null;
}

public Iterator<?> iteratorDFS(Object startVertex) {

    return null;
}

public boolean isEmpty() {
    return size() == 0;
}

public boolean isConnected() {

    return false;
}

public int size() {

    return 0;
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T12:33:41+00:00Added an answer on May 27, 2026 at 12:33 pm

    You can enclose your graph in class:

    class Graph {
        //Map of adjacency lists for each node
        Map<Integer, List<Integer>> adj;
    
        public Graph(int[] nodes) {
            //your node labels are consecutive integers starting with one. 
            //to make the indexing easier we will allocate an array of adjacency one element larger than necessary
            adj = new HashMap<Integer, LinkedList<Integer>>();
            for (int i = 0; i < nodes.length; ++i) {
                adj.put(i, new LinkedList<Integer>());
            }
        }
    
        public addNeighbor(int v1, int v2) {
            adj.get(v1).add(v2);
        }
    
        public List<Integer> getNeighbors(int v) {
            return adj.get(v);
        }
    
    }
    

    And then read it more or less like this:

    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new StreamReader(System.in));
            String line = br.readLine();
    
    
            if (line != null) {
                //read nodes
                String[] nodeNames = line.split(" ");
                int[] nodes = new int[nodeNames.length]
                for (int i = 0; i < nodes.length; ++i) {
                   nodes[i] = Integer.parseInt(nodeNames[i]);
                }
    
                //create graph
                Graph g = new Graph(nodes);
    
                //read edges
                while((line = br.readLine()) != null) {
                    String[] tokens = line.split(" ");
                    int v1 = Integer.parseInt(tokens[0]);
                    int v2 = Integer.parseInt(tokens[1]);
    
    
                    //we add neighbor to each node in both directions.
                    g.addNeighbor(v1, v2);
                    g.addNeighbor(v2, v1);
                }
    
            }
            br.close();
        }
        catch(exceptions) {
            handle them
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Does anyone know how can I using jquery to retrieve the data from the
Does anyone know where can I find recent data on PHP4 vs PHP5 market
Anyone know where i can find a list of the columns for setting the
Does anyone know a resource where we can obtain FREE C++ libraries for MATLAB
im using iphone sdk 3.1.2 Does anyone know how to programatically obtain the name
Does anyone know how I can obtain latitude and longtitude from the Country Name
Does anyone know how can I cut a string and then assign into an
Does anyone know how can I detect the browser type in css? What I
Does anyone know how can I catch a mail error (error is displayed while
Does anyone know how can I edit a subitem on a listView? I've tried

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.