r/learnjava • • Apr 23 '21

Please roast my first attempt at Java!

Coming from C and C++ and just got my first Java program to compile. Generics are actually not like templates! ;) How bad is it in the eyes of a Java programmer? What are the key mistakes I should avoid to eventually find the Java way. Generics used correctly? Anti patterns?

Program is just a graph data structure and a breadth first searcher.

import java.io.*;
import java.util.Vector;
import java.util.LinkedList;
import java.util.Queue;
import java.util.HashMap;
import java.util.Collection;

enum Color { white, grey, red, black }
enum Control { accept, discard }

interface Vertex {}
interface Edge {}

abstract class Visitor
{
    public void start(Vertex root) {}
    public void finish() {}
    
    public Control vertex(Vertex v) { return Control.accept; }
    public Control edge(Edge e, Color col) { return Control.accept; }
}

interface Graph<GraphProperty, VertexProperty, EdgeProperty>
{
    GraphProperty property();
    void property(GraphProperty x);
    VertexProperty property(Vertex v);
    void property(Vertex e, VertexProperty prop);
    EdgeProperty property(Edge e);
    void property(Edge v, EdgeProperty prop);
    Vertex addVertex(VertexProperty x);
    void removeVertex(Vertex x);
    Edge addEdge(
        Vertex from,
        Vertex to,
        EdgeProperty prop);
    void removeEdge(Edge x);
    void clear();
    boolean isEmpty();
    int vertexCount();
    int edgeCount();
    Collection<Vertex> vertices();
    Collection<Edge> edges();
    Collection<Edge> inEdges(Vertex v);
    Collection<Edge> outEdges(Vertex v);
    int index(Vertex v);
    int index(Edge e);
    int inDegree(Vertex v);
    int outDegree(Vertex v);
    int Degree(Vertex v);
    Vertex source(Edge e);
    Vertex target(Edge e);
    void bfs(Vertex root, Visitor vis);
}

abstract class AbstractGraph<GraphProperty, VertexProperty, EdgeProperty>
    implements Graph<GraphProperty, VertexProperty, EdgeProperty>
{
    public abstract class AbstractVertex implements Vertex
    {
        private VertexProperty property_;
        
        protected int index_;
        
        public AbstractVertex(VertexProperty prop, int index__)
        {
            property_ = prop;
            index_ = index__;
        }
    }
    
    public abstract class AbstractEdge implements Edge
    {
        private EdgeProperty property_;
        
        protected Vertex src_, trg_;
        protected int index_;
        
        public AbstractEdge(EdgeProperty prop, Vertex from, Vertex to, int index__)
        {
            property_ = prop;
            src_ = from;
            trg_ = to;
            index_ = index__;
        }
    }
    
    private GraphProperty property_;
    
    protected AbstractGraph(GraphProperty prop)
    {
        property_ = prop;
    }
    
    public GraphProperty property() { return property_; }
    public void property(GraphProperty x) { property_ = x; }
    public VertexProperty property(Vertex v) { return ((AbstractVertex)v).property_; }
    public void property(Vertex v, VertexProperty p) { ((AbstractVertex)v).property_ = p; }
    public EdgeProperty property(Edge e) { return ((AbstractEdge)e).property_; }
    public void property(Edge e, EdgeProperty p) { ((AbstractEdge)e).property_ = p; }
    
    public int index(Vertex v) { return ((AbstractVertex)v).index_; }
    public int index(Edge e) { return ((AbstractEdge)e).index_; }
    public int Degree(Vertex v) { return inDegree(v) + outDegree(v); }
    public Vertex source(Edge e) { return ((AbstractEdge)e).src_; }
    public Vertex target(Edge e) { return ((AbstractEdge)e).trg_; }
    
    public void bfs(Vertex root, Visitor vis)
    {
        var q = new LinkedList<Vertex>();
        var col = new HashMap<Vertex, Color>();
        
        vis.start(root);
        
        q.add(root);
        col.put(root, Color.grey);
        
        while(!q.isEmpty())
        {
            Vertex v = q.poll();
            
            switch(vis.vertex(v))
            {
            case accept:
                for(Edge e : outEdges(v))
                {
                    Color c = col.get(target(e));
                    
                    if(null == c) c = Color.white;
                    
                    Control res = vis.edge(e, c);
                    
                    if(Control.discard == res)
                    {
                        col.put(target(e), Color.black);
                        c = Color.black;
                    }
                    else if(Color.white == c)
                    {
                        col.put(target(e), Color.grey);
                        q.add(target(e));
                    }
                }
                break;
            case discard: break;
            }
            
            col.put(v, Color.black);
        }
        
        vis.finish();
    }
}

class ConcreteGraph<GraphProperty, VertexProperty, EdgeProperty>
    extends AbstractGraph<GraphProperty, VertexProperty, EdgeProperty>
{
    public class MyVertex extends AbstractVertex
    {
        private Vector<Edge> in_;
        private Vector<Edge> out_;
        
        public MyVertex(VertexProperty prop, int index__)
        {
            super(prop, index__);
            in_ = new Vector<Edge>();
            out_ = new Vector<Edge>();
        }
    }
    
    public class MyEdge extends AbstractEdge
    {
        public MyEdge(
            EdgeProperty prop,
            Vertex from,
            Vertex to,
            int index__)
        {
            super(prop, from, to, index__);
        }
    }
    
    public GraphProperty property;
    
    private Vector<Vertex> vertices_;
    private Vector<Edge> edges_;
    
    public ConcreteGraph(GraphProperty prop)
    {
        super(prop);
        vertices_ = new Vector<Vertex>();
        edges_ = new Vector<Edge>();
    }
    
    public Vertex addVertex(VertexProperty prop)
    {
        var V = new MyVertex(prop, vertices_.size());
        vertices_.add(V);
        return V;
    }
    
    public void removeVertex(Vertex v__)
    {
        var v = (MyVertex)v__;
        
        while(!v.out_.isEmpty())
        {
            var e = (MyEdge)v.out_.lastElement();
            
            edges_.remove(e.index_);
            
            for(var ee : edges_.subList(e.index_, edges_.size()))
            {
                ((MyEdge)ee).index_--;
            }
            
            ((MyVertex)e.trg_).in_.remove(e);
            
            v.out_.remove(v.out_.size()-1);
        }
        while(!v.in_.isEmpty())
        {
            var e = (MyEdge)v.in_.lastElement();
            
            edges_.remove(e.index_);
            
            for(var ee : edges_.subList(e.index_, edges_.size()))
            {
                ((MyEdge)ee).index_--;
            }
            
            ((MyVertex)e.src_).out_.remove(e);
            
            v.in_.remove(v.out_.size()-1);
        }
        
        vertices_.remove(v.index_);
        
        for(var vv : vertices_.subList(v.index_, vertices_.size()))
        {
            ((MyVertex)vv).index_--;
        }
    }
    
    public Edge addEdge(
        Vertex from__,
        Vertex to__,
        EdgeProperty prop)
    {
        var from = (MyVertex)from__;
        var to = (MyVertex)to__;
        
        var E = new MyEdge(prop, from__, to__, edges_.size());
        from.out_.add(E);
        
        try
        {
            to.in_.add(E);
        }
        catch(Throwable x)
        {
            from.out_.remove(from.out_.size()-1);
            throw x;
        }
        
        try
        {
            edges_.add(E);
        }
        catch(Throwable x)
        {
            from.out_.remove(from.out_.size()-1);
            to.in_.remove(from.in_.size()-1);
            throw x;
        }
        
        return E;
    }
    
    public void removeEdge(Edge e__)
    {
        MyEdge e = (MyEdge)e__;
        
        edges_.remove(index(e));
        
        for(var ee : edges_.subList(e.index_, edges_.size()))
        {
            ((MyEdge)ee).index_--;
        }
        
        ((MyVertex)e.src_).out_.remove(e);
        ((MyVertex)e.trg_).in_.remove(e);
    }
    
    public void clear()
    {
        vertices_.clear();
        edges_.clear();
    }
    public boolean isEmpty() { return vertices_.isEmpty(); }
    
    public int vertexCount() { return vertices_.size(); }
    public int edgeCount() { return edges_.size(); }
    
    public Collection<Vertex> vertices()
    {
        return java.util.Collections.unmodifiableCollection(vertices_);
    }
    public Collection<Edge> edges()
    {
        return java.util.Collections.unmodifiableCollection(edges_);
    }
    public Collection<Edge> inEdges(Vertex v)
    {
        return java.util.Collections.unmodifiableCollection(((MyVertex)v).in_);
    }
    public Collection<Edge> outEdges(Vertex v)
    {
        return java.util.Collections.unmodifiableCollection(((MyVertex)v).out_);
    }
    
    public int inDegree(Vertex v) { return ((MyVertex)v).in_.size(); }
    public int outDegree(Vertex v) { return ((MyVertex)v).out_.size(); }
}

class myvis extends Visitor
{
    Graph g;
    myvis(Graph gg) { g=gg; }
    
    public void start(Vertex root)
    {
        System.out.println("start");
    }
    public void finish()
    {
        System.out.println("finish");
    }
    
    public Control vertex(Vertex v)
    {
        System.out.println(g.index(v));
        return Control.accept;
    }
    public Control edge(Edge e, Color col)
    {
        System.out.println("" + g.index(e) + ": " + g.index(g.source(e)) + " -> " + g.index(g.target(e)) + " " + col);
        return Control.accept;
    }
}

class Test
{
    public static void main(String args[])
    {
        class foo {};
        Graph<foo, foo, foo> g = new ConcreteGraph<foo, foo, foo>(null);
        
        var a = g.addVertex(null);
        var b = g.addVertex(null);
        var c = g.addVertex(null);
        var d = g.addVertex(null);
        g.addEdge(a, b, null);
        g.addEdge(a, c, null);
        g.addEdge(c, d, null);
        g.addEdge(a, c, null);
        g.addEdge(a, c, null);
        g.addEdge(d, a, null);
        g.addEdge(d, d, null);
        
        g.bfs(a, new myvis(g));
    }
}
42 Upvotes

39 comments sorted by

View all comments

27

u/anthropaedic Apr 23 '21

Definitely a c coder’s Java. For variable names, try to be descriptive. See here for some basics.

I am a bit confused why you are implementing interfaces without anything defined in them.

5

u/mikaijin Apr 23 '21

I wanted to get stable refs of vertices and edges and thought it would be a nice idea to give them their own type instead of using a generic Object, if only to aid overloading. There is no interface because they are just handles.

8

u/hugthemachines Apr 23 '21

The comment still stands.

It might be a good idea for you to read the book "clean code" by robert c martin to learn a bit about these things.