Graph Theory Program - java

So right now i'm in a class learning graph theory. I thought it would be cool to make a program for it. To create different graphs, add and deleted nodes, edges and all the sort like that.
This semester I do not have no programming classes, so I'm trying to get ready for next semester when they start up again.
So far what I have is a Class called Graph Theory (Driver/Command-line) which of course runs the whole program.
Besides the driver class the main classes I have are:
--Graph: TYPES: Path, Cycle, Complete...
Because they all have lists of nodes and edges and add/deleted methods in common I made the TYPES, like path and cycle, inherit from graph so I didn't have to remake those million methods for each one.
In the driver class I have a list of all created graphs.
ArrayList<Graph> graphs = new ArrayList<Graph>();
My problem is when I started working on the Partite graph class it inherits from Graph like the others, but I can't access the methods.
I the driver when i create the Partite:
Partite p = new Partite(blah, blah);
graphs.add(p);
When I go through and get this graph from the list I can't access the methods from Partite.
How can I do this.

Because when you get elements from graphs they will be references of type Graph.
To access the methods from Partite you must add a cast to Partite.
Partite p = new Partite(blah, blah);
graphs.add(p);
Partite other = (Partite)graphs.get(0);
other.methodFromPartite();
Done.

Basic solution
If you rely on specific Partite methods (as opposed to Partite's versions of Graph's methods) you shouldn't really be holding it in an array of Graphs but if you must you can cast
Graph g=graphs.get(i);
Partite p=(Partite)g;
Be aware that if you get it wrong (attempt to cast something that isn't a Partite) you will get an exception. You can check in advance if the cast is acceptable by using instanceof
if (g instanceof Partite){
.....
}
A better concept
But as I say all this is usually a sign of bad program design. A better design would be to have only general graph behaviour triggered from reading this list (Partites would still be in the list, but they would behave as Graphs) and a seperate list of Partites being held as well for whatever different behaviour they need
An even better concept
If you can organise your program in such a way that you are only calling methods from Graph but Parties overrides some of them such that it behaves the way you want that is the ideal solution.
For example Graph has update and Partites` overrides update to do the extra work it needs as well. So
public class Graph {
public void update(){
doImportantWork();
}
}
public class Partite extends Graph{
#Override
public void update() {
super.update(); //so that the basic graph behavior happens
doPartiteSpecificImportantWork();
}
}
This is not always practical however.

This is probably because you're trying to modify your Partite object using a Graph reference to it. If you want to call sub class specific methods using parent class references, your design probably needs some modification (this is a code smell). To temporarily get around it for now you can case your Graph reference to a Partite reference.
((Partite)graphRef).[some method on partite]

Related

Let callables/threads work on copy of an object in Java

I have a working code, in which I calculate the shortest path from every point (Dijkstra's algorithm) to every point in a graph.
But as soon as I want to use more than 1 thread with my ExecuterService, they all will work on the same graph for calculating the results, which of course makes the result unusable.
How can I make it so that one thread gets an own copy of the graph, so the callables run on that thread won't disturb the others? Is that even possible?
As Keqiang Li commented, you need to define a mechanism for copying the single graph data structure you already have. However, since you obviously need to first build the structure itself before creating multiple copies of it, one commonly-used trick is to use a builder pattern in order to create immutable objects on which you will actually do the search. Note that this needn't be implemented in an actual separate e.g. GraphBuilder class but rather you can simply implement a mechanism for creating immutable copies of a single mutable graph structure which you initially build incrementally while reading in your data:
public class MutableDirectedGraph implements DirectedGraph {
public MutableDirectedGraph() {
...
}
public Edge addEdge(final Node start, final Node end, final String label, final double weight) {
...
}
public Node addNode() {
...
}
...
}
public class ImmutableDirectedGraph implements DirectedGraph {
public ImmutableDirectedGraph(final DirectedGraph copyee) {
...
}
...
}
One nice thing about this approach is that you can implement MutableDirectedGraph to be easy to modify/build in an incremental fashion and then implement ImmutableDirectedGraph with optimizations for searching (e.g. storing Edge objects by their respective IDs in an array for memory-efficient storage while using Map-based storage in the mutable version). In this way, making two separate classes for two specific tasks may be quicker for the programmer as well as for the computer to deal with.

How can I reuse collections that would use the same backing iterator?

I'm fairly new to Java so my knowledge is pretty limited. I'm working on a personal project where I'm trying out some of the techniques used in Guava for creating views/transformations of collections. I made a class called View to take an inputted collection as the backing iterable, and a transformation, and then present it as a read-only iterable. (not a collection, though I don't think it makes much of a difference for this question). Here is a quick example of using it...
public class Node {
public enum Change implements Function<Node, Coordinate> {
TO_COORDINATE;
#Override public Coordinate apply(Node node) {
return new Coordinate(node);
}
}
private HashSet<Node> neighborNodes = new HashSet<Node>();
//various other members
public View<Coordinate> viewNeighborCoordinates() {
return new View<Coordinate>(neighborNodes, Change.TO_COORDINATE);
}
}
now if some method wants to use viewNeighborCoordinates() of this node, and then later some other method also wants to viewNeighborCoordinates() of this node, it seems wasteful to always be returning new objects, right? I mean any number of things should be able to share reference to a view of the same backing iterable with the same transformation, since all they're doing is reading through it. Is there an established way of managing a shared pool of objects which can be "interned" like Strings are? Is it just having to make some sort of ViewFactory that stores a running list of views in use, and everytime someone wants a view, it checks to see if it already has that view and hands it out? (is that even more efficient)?
As already stated, interning is possible (look at Interners), but most probably a bad idea.
Another possibility is lazy initialization of a field storing the View. Since I'm lazy as well, I only point you to a Lombok implementation. Be careful with DCL, if you want to try this. In case your class is immutable, you may need no synchronization at all, like e.g. String.hashCode.
A very simple possibility is eager initialization of a field. Assuming you need the view often, it's the best way.
But without knowing more, your current implementation is best. Beware the root of all evil.
Don't optimize without profiling or benchmarking (and if you benchmark, then do it right, i.e., using caliper or jmh. Home-baked benchmarking in Java just doesn't work).

Preserving encapsulation of a generic in Java

Good evening.
I have a rather involved question. To practice Java, I've been re-implementing some of the data structures in the standard library. Stacks, LinkedLists, Trees, etc. I just established, through a very simple example, that the java.util.Stack class performs a deep copy when either the peek() or pop() methods are used. This is understandable, since the goal would be to protect the contents of the class from outside interference. So far, in my own implementation of the Stack (a naive implementation with a simple array, linked lists will come later), I have not cared for this at all:
public class ArrayStack<T> implements Stack<T> {
private T[] data; // Will expand the array when stack is full.
private int top; // serves as both top and count indicator.
...
...
#Override
public T pop() throws EmptyStackException {
if(top == -1)
throw new EmptyStackException("Stack is empty.");
return data[top--]; // Shallow copy, dangerous!
}
Unfortunately, since a generic cannot be instantiated, I cannot assume a copy constructor and do stuff like return new T(data[top--]); I've been looking around in S.O and I've found two relevant threads which attempt to solve the problem by using some variant of clone(). This thread suggests that the class's signature be extended to:
public class ArrayStack<T extends DeepCloneableClass> implements Stack<T>
...
where DeepCloneableClass is a class that implements an interface that allows for "deep cloning" (see the top response in that thread for the relevant details). The problem with this method, of course, is that I can't really expect from standard classes such as String or Integer to be extending that custom class of mine, and, of course, all my existing jUnit tests are now complaining at compile-time, since they depend on such Stacks of Integers and Strings. So I don't feel as if this solution is viable.
This thread suggests the use of a third-party library for cloning pretty much any object. While it appears that this library is still supported (latest bug fixes date from less than a month ago), I would rather not rely on third-party tools and use whatever Java can provide for me. The reason for this is that the source code for these ADTs might be someday shared with undergraduate college students, and I would rather not have them burdened with installing extra tools.
I am therefore looking for a simple and, if possible, efficient way to maintain a generic Java data structure's inner integrity while still allowing for a simple interface to methods such as pop(), peek(), popFront(), etc.
Thanks very much for any help!
Jason
Why do you need to clone the objects?
Your stack just has a collection of references. You probably don't need to clone them, just make a new array and put the appropriate references in it, then throw away the old array.
Integer, Strings, etc are all immutable, so their contents are safe by design.
As for custom objects, while experienced Java Programmers will certain have mixed feelings about it, implementing a custom interface is certainly one way to approach the problem.
Another one is to make <T extends Serializable> (which is implemented by Integer, String, etc) and "clone" through serialization.
But if you want to teach your students the "right way" I would definitively use a third party library... You can just create a lib folder in your project and configure you build tool / IDE to add the needed jars to the Classpath using relative paths, so your undergraduate students will not have to install or setup anything.
Just for reference, this question may be very useful.
I've been teaching Java introductory classes (as an IT Instructor / not as a college Professor) using this kind of approach, and it is way less painful than it sounds.
The comments helped me understand what I had wrong. I was using the following example to "prove" to myself and others that the Java Standard Library's Collections do a deep copy when providing references to objects in the Collection:
import java.util.Stack;
public class StackTestDeepCopy {
public static void main(String[] args){
Stack<String> st = new Stack<String>();
st.push("Jim");
st.push("Jill");
String top = st.peek();
top = "Jack";
System.out.println(st);
}
}
When printing st, I saw that objects had been unchanged, and concluded that a deep copy had taken place. Wrong! Strings are immutable, and therefore the statement top = "Jack" does not in any way modify the String (not that any Object would be "modified" by a statement like that, but I wasn't thinking straight), it just makes the reference point to a new place on the heap. A new example, involving an actually mutable class, made me understand the error in my ways.
Now that this problem has been solved, I'm quite baffled by the fact that the standard library allows for this. Why is it that accessing elements in the standard library is implemented as a shallow copy? Sounds very unsafe.
java.util.Stack doesn't do a deep copy:
import java.util.Stack;
public class Test {
String foo;
public static void main(String[] args) {
Test test = new Test();
test.foo = "bar";
Stack<Test> stack = new Stack<Test>();
stack.push(test);
Test otherTest = stack.pop();
otherTest.foo = "wibble";
System.out.println("Are the same object: "+(test.foo == otherTest.foo));
}
}
Results in:
Are the same object: true
If it did do a copy then test and otherTest would point to a different object. A typical stack implementation simply returns a reference to the same object that was added onto the stack, not a copy.
You probably also want to set the array item to null before returning, otherwise the array will still hold a reference to the object.

How do I get the object stored in a field, to then get its class, then get the fields of that class etc? (Recursively obtain fields of classes)

Quick edit: As was pointed out below I should be doing a BFS but I need a point to stop retrieving new fields, which I haven't had time to think about yet. Thanks for all the help!
I'm trying to use Java reflection to recursively get the fields of classes, essentially creating a tree to display
Class
field1 class
field1.1 class
field1.2 class
field2 class
field 2.1 class
field 2.2 class
This is for a recursive decent parser, so I figured a recursive display function would be cool to make. Unfortunately it's crushing me.
Example class Foo, with fields of Class1 and Class2, each of which could have more fields of different classes:
class Assignment extends Statement {
Variable target;
Expression source;
Assignment (Variable t, Expression e) {
target = t;
source = e;
}
My recursive method:
private void recurse(Object object){
System.out.println(object.getClass());
for (Field field : object.getClass().getDeclaredFields()){
System.out.println(field.getType());
System.out.println(field.getName());
if(!field.getType().isPrimitive() || field.getType() instanceof Class || field.getName() != "clazz"){
//recurse(field);
}
}
The println has been for testing and an example output for Foo would be (without recursion, it seems to work) giving
class Assignment
class Variable
target
class Expression
source
But I can't figure out how to take the Variable class and then get its fields and so on. The field that contains this information gives me a class Field.
Also, I realize I need a point to stop the recursion but stopping at primative fields doesn't seem to work. Any suggestions would be useful and really help me understand the nitty-gritty of what I seem to be flailing around in.
Side note: for the means of this class that this is for I know I can just put a display method in for each class and call those, but I the process of reflection seemed more interesting and possibly reusable.
TLDR: How do I get the class of the actual field contained in a Field?
Sorry if I'm missing anything, first question I've asked.
Thanks for your time!
-Alex
Well, you are describing a graph, and a search algorithm in it.
Your graph is G=(V,E) where V = {all object types } and E = { (u,v) | u has a field of type v }.
You can use BFS to "explore" your graph from a single source, and get all "accessable vertices [types]" from it [the single source].
BFS holds a visited set, and avoids exploring vertices [types] that were already explored, and it [BFS] stops, when there is nothing new to discover [the queue is empty].
The same thing can be done with DFS, but again - you are going to need a visited set, in order to avoid infinite loops when the graph has cycles [for example: in some implementations of composite classes, such as a tree, where each Node contains a Node itself].
Because you're recurring right away, you're going to go all the way down to Object on the first field of the top level class before moving on to the next. In other word, you're doing a Depth First Search.
You're looking for an output that's more like a Breadth First Search. This will involve using a queue and adding new classes to the end and popping off the next to process instead of using recursion.
You've managed to get this far so I'm not going to spell the whole thing out for you, I'm sure there's enough here to pick the rest up.

"Leaking this" from a Design Standpoint

Warning: Leaking "this" in constructor
I keep running into this, and I have a nagging feeling that it's because my design is wrong or not optimal.
I understand that this warning is bringing to my attention the fact that I am allowing access to an object that is potentially not fully initialized.
Let's say that I need a Frame that HAS and requires a List (Frame(List list)). In List, I might want to do something such as add(). In order to make sure Frame knows as little about List as possible (only that it has one), I would want to access the containing Frame from the List (List HAS a Frame?). This seems a little silly, but I have 2+ implementations of List that will use Frame in different ways..
To ensure that my code is used properly, I would require a Frame in the constructor of List.
I would also require a List in the constructor of Frame, as it MUST have one:
public abstract class Frame {
private final List list;
public Frame(List list) {
this.list = list;
list.setFrame(this);
}
}
public abstract class List {
private Frame frame;
protected final void setFrame(Frame frame) {
this.frame = frame;
}
}
So, is this bad design, or should I really create some intermediate scaffolding that does this, or even leave the scaffolding to the user?
Thanks!
Introduce a factory method:
public static Frame createFrame(List list) {
Frame frame = new Frame(list);
list.setFrame(frame);
}
private Frame(List list) {
this.list = list;
}
This does not leak this, and always makes sure everything is configured correctly without the need for every caller to remember initializing both sides of the association.
I think that this sort of "doubly linked" structure, where a Frame points to a List that points back to its parent Frame, is something you ought to avoid unless you have a specific need for it. You should if possible try and make one of the two objects the "parent" that points to the "child."
It's a bit hard to understand at first why the double-linking is not such a great idea, but here are some reasons:
In a structure with clear parent-child relationships, it's trivial to reuse the same child objects in more than one parent. In a double-linked structure, on the other hand, if you want to create a new structure that shares some of the elements from an original, you either have to create new copies of the elements of interest, or you have to destroy the original structure.
There are many design patterns that rely on a clear chain of "command" in an object graph, and the double-linked structures obscure that chain of command from readers of the code.
A lot of the cases where processing of a child requires knowledge about the parent in which that child appears are better handled by passing the parent as a "context" argument to a method that processes the child. The classic example of this pattern is in interpreters, where evaluation of an expression takes as an argument an "environment" that contains all the of the outside information necessary to evaluate a child expression. (Or alternatively, you use a stateful Iterator or Hierarchical Visitor that navigates the structure and keeps track of location.)
This is not to say that the double-linked structures are never appropriate, but rather that the simpler, single-linked structures should probably be the first choice.

Categories

Resources