org.glassfish.pfl.basic.algorithm.Graph Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of webservices-rt Show documentation
Show all versions of webservices-rt Show documentation
This module contains the Metro runtime code.
/*
* Copyright (c) 2007, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.glassfish.pfl.basic.algorithm ;
import java.util.List ;
import java.util.Collection ;
import java.util.Collections ;
import java.util.Set ;
import java.util.HashSet ;
import java.util.ArrayList ;
import org.glassfish.pfl.basic.func.UnaryFunction;
public class Graph {
/** A Finder finds the immediate successors of an element of the graph.
*/
public interface Finder extends UnaryFunction> {}
private Set roots ;
private List preorderTraversal = null ;
private List postorderTraversal = null ;
private void traverse( final E node, final Set visited, final Finder finder ) {
if (!visited.contains( node )) {
visited.add( node ) ;
preorderTraversal.add( node ) ;
for (E child : finder.evaluate(node)) {
traverse( child, visited, finder ) ;
}
postorderTraversal.add( node ) ;
}
}
private void init( final Collection roots, final Finder finder ) {
this.roots = new HashSet( roots ) ;
this.roots = Collections.unmodifiableSet( this.roots ) ;
this.preorderTraversal = new ArrayList() ;
this.postorderTraversal = new ArrayList() ;
final Set visited = new HashSet() ;
for (E node : this.roots) {
traverse( node, visited, finder ) ;
}
this.preorderTraversal = Collections.unmodifiableList( this.preorderTraversal ) ;
this.postorderTraversal = Collections.unmodifiableList( this.postorderTraversal ) ;
}
public Graph( final Collection roots, final Finder finder ) {
init( roots, finder ) ;
}
public Graph( final E root, final Finder finder ) {
final Set roots = new HashSet() ;
roots.add( root ) ;
init( roots, finder ) ;
}
public Set getRoots() {
return roots ;
}
public List getPreorderList() {
return preorderTraversal ;
}
public List getPostorderList() {
return postorderTraversal ;
}
}