I have a class that has an enum declared in it, like this:
private enum Marker {
NONE {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
return null;
}
},
STRING {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = value;
buf[COLUMN_VALUE_FLOAT] = "";
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
},
FLOAT {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = "";
buf[COLUMN_VALUE_FLOAT] = value;
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
};
public abstract String[] createResultLine(String columnName, String value, String[] buf);
}
and here is the complete class and the usage
final class CSVDataModifier {
private final Path src;
private int rowNumber = 0;
private static String blockId = "" ;
private static String pipelineId = "" ;
private static String ElasticHostURL = "";
public CSVDataModifier(Path src, /*Path dest, */ String b_id, String p_id, String elasticUrl) {
this.src = src;
this.blockId = b_id;
this.pipelineId = p_id;
this.ElasticHostURL = elasticUrl;
}
private static final int ROW_NUMBER = 0;
private static final int COLUMN_NAME = 1;
private static final int COLUMN_VALUE_STRING = 2;
private static final int COLUMN_VALUE_FLOAT = 3;
private static final int BLOCK_ID = 4;
private static final int PIPELINE_ID = 5;
private static final String[] COLUMN_NAMES = { "row_number", "column_name", "column_value_string", "column_value_float", "blockId", "pipelineId" };
private ExecutorService executorService = Executors.newFixedThreadPool( 100 );
public void apply() throws IOException, InterruptedException {
try (CSVReader reader = new CSVReader(new FileReader(src.toFile())))
{
List<String[]> csvLines = new ArrayList<>();
// key - ordered list of columns in source file
Map<String, Marker> columnNameFloatMarker = getSourceColumnNamesWithFloatMarker(reader.readNext());
int posRowNumber = getRowNumberPosition(columnNameFloatMarker.keySet());
if (columnNameFloatMarker.isEmpty()) {
System.out.println( "empty!" );
return;
}
String[] buf = new String[COLUMN_NAMES.length];
reader.forEach(values -> {
buf[ROW_NUMBER] = values[posRowNumber];
int col = 0;
String[] resultLine;
for (Map.Entry<String, Marker> entry : columnNameFloatMarker.entrySet()) {
String columnName = entry.getKey();
Marker marker = entry.getValue();
if ((resultLine = marker.createResultLine(columnName, values[col], buf)) != null) {
// writer.writeNext( resultLine );
csvLines.add( resultLine );
rowNumber++;
}
col++;
}
if (csvLines.size() >= 75)
{
List<String[]> tmp = new ArrayList<>( );
tmp.addAll( csvLines );
csvLines.clear();
executorService.execute(new BulkThread(ElasticHostURL, new ArrayList<>( tmp )));
}
});
if (csvLines.size() > 0) {
List<String[]> tmp = new ArrayList<>( );
tmp.addAll( csvLines );
csvLines.clear();
executorService.execute(new BulkThread(ElasticHostURL, new ArrayList<>( tmp )));
}
}
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.println( "Total Lines: " + rowNumber );
}
private static final String FLOAT = "_float";
private static final String STRING = "_string";
private enum Marker {
NONE {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
return null;
}
},
STRING {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = value;
buf[COLUMN_VALUE_FLOAT] = "";
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
},
FLOAT {
#Override
public String[] createResultLine(String columnName, String value, String[] buf) {
buf[COLUMN_VALUE_STRING] = "";
buf[COLUMN_VALUE_FLOAT] = value;
buf[COLUMN_NAME] = columnName;
buf[BLOCK_ID] = blockId;
buf[PIPELINE_ID] = pipelineId;
return buf;
}
};
public abstract String[] createResultLine(String columnName, String value, String[] buf);
}
// Source column pre-processing to avoid string comparision;
private static Map<String, Marker> getSourceColumnNamesWithFloatMarker(String... columns) {
if (columns == null || columns.length == 0)
return Collections.emptyMap();
Map<String, Marker> map = new LinkedHashMap<>();
for (int i = 0; i < columns.length; i++) {
String columnName = columns[i];
Marker marker = Marker.NONE;
if (columnName.endsWith(FLOAT)) {
columnName = columnName.substring(0, columnName.length() - FLOAT.length());
marker = Marker.FLOAT;
} else if (columnName.endsWith(STRING)) {
columnName = columnName.substring(0, columnName.length() - STRING.length());
marker = Marker.STRING;
}
if (map.put(columnName, marker) != null)
throw new IllegalArgumentException("Column duplication in the source file");
}
return map;
}
private static int getRowNumberPosition(Set<String> columnNames) {
int i = 0;
for (String columnName : columnNames) {
if ("row_number".equals(columnName))
return i;
i++;
}
throw new IllegalArgumentException("Source file does not contain 'row_number' column");
}
}
The problem is that the private members
private static String blockId = "" ;
private static String pipelineId = "" ;
can't be referenced in the private enum Marker if they're not static, and also they're being initialized in the constructor
public CSVDataModifier(Path src, /*Path dest, */ String b_id, String p_id, String elasticUrl) {
this.src = src;
this.blockId = b_id;
this.pipelineId = p_id;
this.ElasticHostURL = elasticUrl;
}
I can see the only way to do that, to declare the private member not as static , is to turn the private enum Marker into an internal class or maybe something else.
Since I'm new to Java and to the OOP world, can I get any guidance to solve this issue?
This code is quite hardcore and needs massive refactoring because it is violating most of programming principles
The answer for your question is to extract those fields to another class like ModifierSetup and provide it to the createResultLine as a parameter
public class ModifierSetup {
private String pipelineId;
private String ElasticHostURL;
// all args constructor
}
// inside your CSVDataModifier
private ModifierSetup setup;
public CSVDataModifier(Path src, /*Path dest, */ String b_id, String p_id, String elasticUrl) {
this.src = src;
this.blockId = b_id;
this.setup = new ModifierSetup(p_id, elasticUrl);
}
// ...
if ((resultLine = marker.createResultLine(columnName, values[col], buf, this.setup)) != null) {
// ...
public abstract String[] createResultLine(String columnName, String value, String[] buf, ModifierSetup modifierSetup);
but that's definitely not enough. Many of your fields should be extracted like this. Instead of weird 'singleton' enum implementation you should provide some common interface like
public interface ResultLineCreator {
ResultData createResultLine(ColumnMetaData columnMetaData, ModifierSetup modifierSetup, ResultData result); // in ColumnMetaData you can encapsulate columnName and value, inside ResultData result data
}
and proper local implementations of it, the reader should be wrapped with some kind of supplier etc etc - just think about how many responsibilities this class has - even if you will resolve your problem it won't be working/maintanable/testable/clear
Related
I have a Java class which uses BufferedReader to obtain information from a text file, then store the information into an Array called newData . I want to store a certain part of the information to the VegTypes[f] = new VegType(); but I not sure what code should I write here to obtain that part of information.
Without completing this part, I am not able to continue working on another Array Object which is Vegs[i] = new Veg(newData[0], newData[1], newData[2],); for storing information together with VegTypes Array Object.
Below is my code of the Java class:
public class theVegetable {
private Veg[] Vegs;
private VegType[] VegTypes;
public theVegetable() {
int quantity;
int vegQuantity;
String vegLine;
try {
BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
quantity = Integer.parseInt(vegLine.readLine());
Vegs = new Veg[quantity];
for (int i = 0; i < quantity; i++) {
vegLine = br.readLine();
String[] newData = vegLine.split(";");
vegQuantity = Integer.parseInt(newData[3]);
//For loop to store information into VegTypes
for (int f = 0; j < vegQuantity; f++) {
VegTypes[f] = new VegType();
}
//Vegs Array Object to store information plus VegTypes
Vegs[i] = new Veg(newData[0], newData[1], newData[2],);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
Below is my vegetableInfo.txt text file:
3
Tomato;class1;Malaysia Tomato;2;MT100A;MT1;200;90;MT20A;MT2;600;80;Malaysia product
Avocado;class2;Europe Avocado;4;EA100A;EA1;300;90;EA14A;EA2;90;80;EA230A;EA3;43;50.9;EA470A;EA4;400;76;Europe product
Cabbage;class3;Malaysia Cabbage;3;MC100A;MC1;500;20;MC49A;MC2;500;50;MC800A;MC3;600;10.3;Malaysia product
The number 3 at the top of the text file is for the int quantity; variable to store the amount.
The kind of information I want the VegTypes[f] = new VegType(); to store are MT100A;MT1;200;90;MT20A;MT2;600;80;, the number 2 besides the Malaysia Tomato are for int vegQuantity; variable. Same thing goes for other vegetables in the text file.
Constructor of my private VegType[] VegTypes; Array Object:
private String vegCode;
private String vegBatch;
private int vegBatchQuantity;
private double vegGrade;
public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
vegCode = inVegCode;
vegBatch = inVegBatch;
vegBatchQuantity = inVegBatchQuantity;
vegGrade = inVegGrade;
}
My Veg Class:
public class Veg {
private String vegetableName;
private String classLevel;
private String productionCountry;
private VegType[] VegTypes;
private String productType;
//Constructor
public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
vegetableName = inVegetableName;
classLevel = inClassLevel;
productionCountry = inProductionCountry;
vegType = inVegTypes;
productType = inProductType;
}
public String getVegetableName() {
return vegetableName;
}
public String getClassLevel() {
return classLevel;
}
public String getProductionCountry() {
return productionCountry;
}
public String getProductType() {
return productType;
}
}
This is wrong:
//For loop to store information into VegTypes
for (int f = 0; j < vegQuantity; f++) {
VegTypes[f] = new VegType();
}
you need to use f to adjust the index into your array of fields.
for (int f = 0; j < vegQuantity; f++) {
String vegCode = newLine[f*4 + 4];
String vegBatch = newLine[f*4 + 5];
int vegQuantity = Integer.parse(newLine[f*4 + 6]);
double vegGrade = Double.parse(newLine[f*4 + 7]);
VegTypes[f] = new VegType(vegCode, vegBatch, vegQuantity, vegGrade);
}
class VegType {
private String vegCode;
private String vegBatch;
private int vegBatchQuantity;
private double vegGrade;
public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
vegCode = inVegCode;
vegBatch = inVegBatch;
vegBatchQuantity = inVegBatchQuantity;
vegGrade = inVegGrade;
}
#Override
public String toString() {
return vegCode+" "+vegBatch+" "+vegBatchQuantity+" "+vegGrade;
}
}
class Veg {
private String vegetableName;
private String classLevel;
private String productionCountry;
private VegType[] VegTypes;
private String productType;
//Constructor
public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
vegetableName = inVegetableName;
classLevel = inClassLevel;
productionCountry = inProductionCountry;
VegTypes = inVegTypes;
productType = inProductType;
}
#Override
public String toString() {
return vegetableName+" "+classLevel+" "+productionCountry+" "+VegTypes+" "+productType;
}
public String getVegetableName() {
return vegetableName;
}
public String getClassLevel() {
return classLevel;
}
public String getProductionCountry() {
return productionCountry;
}
public String getProductType() {
return productType;
}
}
class TheVegetable {
private Veg[] Vegs;
private VegType[] VegTypes;
public TheVegetable() throws IOException {
int quantity;
int vegQuantity;
String vegLine;
try {
BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
quantity = Integer.parseInt(br.readLine());
Vegs = new Veg[quantity];
for (int i=0; i<quantity; i++) {
vegLine = br.readLine();
String[] newData = vegLine.split(";");
vegQuantity = Integer.parseInt(newData[3]);
VegTypes=new VegType[vegQuantity];
for(int j=4, k=0; j<newData.length-1; j+=4, k++) {
VegTypes[k] = new VegType(newData[j], newData[j+1], Integer.parseInt(newData[j+2]), Double.parseDouble(newData[j+3]));
}
Vegs[i]=new Veg(newData[0], newData[1], newData[2], VegTypes, newData[newData.length-1]);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
I just did a company online and i couldnt get this question right..
looking to improve for next online assessment.
question is:
your given 1 input string where the format is like this:
current:target
where current = Company,Stock or Bond,amount
and target = Company,Stock or Bond,amount
and the ':' separates current and target
an example is:
Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15
the output should be a string that makes the input meet the output for this case its going to be:
SELL,Google,STOCK,5
BUY,Vodafone,STOCK,5
as you can see the ouput should be in alphabetical order (google is before vodafone) and also bonds should appear before stocks.
here is some setup code to help you:
public class main {
public static void main(String[] args){
String input = "Vodafone,STOCK,10|Google,STOCK,15|Microsoft,BOND,15:Vodafone,STOCK,15|Google,STOCK,10|Microsoft,BOND,15";
String output = matchBenchmark(input);
System.out.println(output);
}
public static String matchBenchmark(String input){
}
}
You should probably parse the input into a map:
Map keys should be <company>,<type>
Map values can be {<current-value>,<new-value>}
Then iterate over the map (you probably want to sort the keys) and print SELL or BUY according to the different between the current and new value.
Smth. like that:
public final class Market {
private final Pattern patternLine = Pattern.compile("(?<current>.+):(?<target>.+)");
private final Pattern patternData = Pattern.compile("(?<name>\\w+),(?<active>\\w+),(?<amount>[-]?\\d+)");
private final Pattern patternDataSplit = Pattern.compile("\\|");
public String matchBenchmark(String input) {
Matcher matcher = patternLine.matcher(input);
if (!matcher.matches())
throw new IllegalArgumentException();
Map<String, Data> current = getData(matcher.group("current"));
Map<String, Data> target = getData(matcher.group("target"));
return calc(current, target).stream()
.map(data -> data.getName() + ',' + data.getActive() + ',' + data.getAmount())
.collect(Collectors.joining("\n"));
}
private Map<String, Data> getData(String str) {
return Arrays.stream(patternDataSplit.split(str))
.map(patternData::matcher)
.filter(Matcher::matches)
.map(m -> new Data(m.group("name"), m.group("active"), Integer.parseInt(m.group("amount"))))
.collect(Collectors.toMap(Data::getName, Function.identity()));
}
private static final String BUY = "BUY";
private static final String SELL = "SELL";
private static Queue<Data> calc(Map<String, Data> current, Map<String, Data> target) {
Queue<Data> queue = new PriorityQueue<>(Data.SORT_BY_NAME_ACTIVE_ASC);
Set<String> names = new HashSet<>(current.keySet());
names.addAll(target.keySet());
for (String name : names) {
Data dataCurrent = current.get(name);
Data dataTarget = target.get(name);
if (dataCurrent == null) {
if (dataTarget.amount != 0)
queue.add(new Data(dataTarget.amount > 0 ? BUY : SELL, dataTarget.name, Math.abs(dataTarget.amount)));
} else if (dataTarget == null) {
if (dataCurrent.amount != 0)
queue.add(new Data(dataCurrent.amount > 0 ? SELL : BUY, dataCurrent.name, Math.abs(dataCurrent.amount)));
} else if (dataCurrent.amount != dataTarget.amount)
queue.add(new Data(dataTarget.amount > dataCurrent.amount ? BUY : SELL, dataCurrent.name,
Math.abs(dataTarget.amount - dataCurrent.amount)));
}
return queue;
}
public static final class Data {
public static final Comparator<Data> SORT_BY_NAME_ACTIVE_ASC = Comparator.comparing(Data::getActive).thenComparing(Data::getName);
private final String name;
private final String active;
private final int amount;
public Data(String name, String active, int amount) {
this.name = name;
this.active = active;
this.amount = amount;
}
public String getName() {
return name;
}
public String getActive() {
return active;
}
public int getAmount() {
return amount;
}
}
}
this is a part of my code :
public static final int HAUTE_IMPORTANCE = 1;
public static final int MOYENNE_IMPORTANCE = 2;
public static final int FAIBLE_IMPORTANCE = 3;
private static int dernierIdAttribue = 0;
private Date dateCreation = Date.dateDuJour();
private Date dateLimite;
private String description;
private int niveauImportance;
private boolean acheve;
private int id;
public Todo (String description, Date dateLimite) throws TodoInvalideException{
if ( dateLimite == null||dateCreation.estEgale(dateLimite) ||!dateCreation.estPlusRecente(dateLimite) && description != null && !description.isEmpty()){
this.description = description;
this.dateLimite = null;
this.niveauImportance = FAIBLE_IMPORTANCE;
acheve = false;
dernierIdAttribue++;
id = dernierIdAttribue;
} else{
throw new TodoInvalideException("Erreur constructeur2");
estPLusRecente & estEgale are 2 class method in class Date.
I know this has been asked a lot in stackoverflow but I could not find answers that work to my problem.
In the following code below, I cant print out each item in ArrayList<Integer> because it says that "Edge cannot be cast to java.lang.Integer".
I have tried to print each item using for(Integer item :p1) and also for (int item: p1) but both did not work.
I think maybe the problem is because of the toString() method in Edge class but if i do not use toString() I cant get the real key number (it will be printed as Edge#28a418fc or something like this)
Thanks for helping before
Main class
public class Ranker7 {
static Graph g;
static Node n;
static Edge e;
static HashMap<Integer, Node> nodeMap;
int id;
static double weight;
static int year;
static int type;
Ranker7() {
g = new Graph();
nodeMap = new HashMap<Integer, Node>();
n = new Node(id,year,type,weight);
}
public static void main (String[] args) throws Exception{
long startTime = System.currentTimeMillis();
/**Rule Mining**/
Ranker7 Ranker = new Ranker7();
Connection connect = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
PreparedStatement preparedStatement2 = null;
ResultSet resultSet2 = null;
HashMap nodeMap = new HashMap();
System.out.println("Processing...");
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");
resultSet = preparedStatement.executeQuery();
int i=0;
while(resultSet.next()) {
g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));
i++;
System.out.println( "edges added to G = "+i);
}
System.out.println("Loaded " + g.nodeCount() + " nodes.");
preparedStatement = connect.prepareStatement("Select node,year,type from subnode2");
resultSet = preparedStatement.executeQuery();
int h=0;
while(resultSet.next()) {
Node n = new Node(resultSet.getInt(1), resultSet.getInt(2),resultSet.getInt(3),weight);
int key1=resultSet.getInt(1);
nodeMap.put(key1,n);
h++;
}
System.out.println(nodeMap);
System.out.println(nodeMap.size());
Scanner sc = new Scanner(System.in);
System.out.println("How many authors do you want to enter?");
int num = sc.nextInt();
int[] authorNames = new int[num];
for(int a = 0; a < authorNames.length; a++){
System.out.println("Enter author name:");
authorNames[a] = sc.nextInt();
}
System.out.println("Year : ");
int inputYear3 = sc.nextInt();
ArrayList<Integer> p1 = new ArrayList<Integer>();
/**Get the papers written by input author A-P**/
for(int b=0; b< authorNames.length;b++){
int AuthorID1 = authorNames[b];
p1 = g.getOutEdgesToP(AuthorID1);
}
for(int item : p1){ //the error of classcastexception is here
System.out.println(item);
}
}
}
Edge class
public class Edge {
int from;
int to;
int type;
private static int counter = 0;
public Edge(int from, int to, int type) {
this.from = from;
this.to = to;
this.type = type;
// System.out.println("edges added from " + from + " to " + to + " with type "+ type);
}
public String toString(){
String repr = Integer.toString(to);
return repr;
}
public int getfrom(){
return from;
}
public int getto(){
return to;
}
public int getType(){
return type;
}
public void setfrom(int from){
this.from = from;
}
public void setto(int to){
this.to = to;
}
public void setType(int type){
this.type = type;
}
}
Graph class
import java.lang.reflect.Field;
import java.util.*;
public class Graph {
private HashSet<Integer> nodeIDs;
public HashMap<Integer, String> nodeIDsWithTN;
public HashMap<Integer, String> TNMap;
private HashMap<Integer, ArrayList<Integer>> edges;
private HashMap<Integer, ArrayList<Integer>> reverse;
private int numNodes;
private int numEdges;
private int numReverse;
public Graph() {
edges = new HashMap<Integer, ArrayList<Integer>>();
reverse = new HashMap<Integer, ArrayList<Integer>>();
nodeIDs = new HashSet<Integer>();
nodeIDsWithTN = new HashMap<Integer, String>();
TNMap = new HashMap<Integer, String>();
new HashSet();
}
public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {
Edge e = new Edge(from,to,T);
nodeIDs.add(e.from);
nodeIDs.add(e.to);
ArrayList tmp = null;
if (edges.containsKey(e.from))
tmp = (ArrayList) edges.get(e.from);
else {
tmp = new ArrayList();
edges.put(e.from,tmp);
}
tmp.add(e);
ArrayList tmp2 = null;
if (reverse.containsKey(e.to))
tmp2 = (ArrayList) reverse.get(e.to);
else {
tmp2 = new ArrayList();
reverse.put(e.to,tmp2);
}
tmp2.add(e);
}
public int nodeCount() {
if(nodeIDs.size() > 0)
return nodeIDs.size();
// else return numNodes;
return numEdges;
}
public int countInEdges(Integer key) {
if (!reverse.containsKey(key)) return 0;
return ((ArrayList<?>) reverse.get(key)).size();
}
public int countOutEdges(Integer key) {
if (!edges.containsKey(key)) return 0;
return ((ArrayList<?>) edges.get(key)).size();
}
/**
public ArrayList<String> getInEdgesFromPtoA(String id) {
if (!reverse.containsKey(id)) return null;
ArrayList<String> a = reverse.get(id);
ArrayList<String> result = new ArrayList<String>();
for(int j=0;j<a.size();j++){
if(a.get(j).startsWith("A")){
result.add(a.get(j));
}
}
return result;
}
**/
public ArrayList<Integer> getOutEdges(Integer key) {
if (!edges.containsKey(key))
return null;
ArrayList<Integer> value = edges.get(key);
return value;
}
public ArrayList<Integer> getOutEdgesToP(int id) {
if (!edges.containsKey(id)) {
return null;
}
ArrayList<Integer> a = edges.get(id);
System.out.println ("Arraylist a: " + a); //if i print using this its okay. but i cant get each item in this ArrayList like below
for(int item : a){ //the error of classcastexception is here
System.out.println(item);
}
return a;
}
public Iterator<Integer> nodeIteratorInitial() {
return nodeIDs.iterator();
}
}
Node class
public class Node {
int id;
double weight;
int year;
int type;
private static int counter = 0;
public Node(int id,int year,int type,double weight) {
this.id = id;
this.year=year;
this.weight = weight;
this.type = type;
}
#Override
public String toString() {
// here you can create your own representation of the object
String repr = "id:" + id + ", year:" + year + ", weight:" + weight + ", node type:" + type;
return repr;
}
public double getWeight(){
return weight;
}
public int getid() {
return id;
}
public int getType() {
return type;
}
public int getYear() {
return year;
}
public void setWeight(double weight){
this.weight=weight;
}
public void setid(int id){
this.id=id;
}
public void setType() {
this.type=type;
}
}
private HashMap<Integer, ArrayList<Integer>> edges;
// ...later
Edge e = new Edge(from,to,T);
// ...later
else {
tmp = new ArrayList();
edges.put(e.from,tmp);
}
tmp.add(e);
Ultimately, this is a classic example of why raw types are bad. You've got an ArrayList<Integer> and you put Edges in it.
Unfortunately, I don't know how to tell you how to fix it since I don't understand what you're trying to do.
the error lies here
public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {
Edge e = new Edge(from,to,T);
nodeIDs.add(e.from);
nodeIDs.add(e.to);
ArrayList tmp = null;
if (edges.containsKey(e.from))
tmp = (ArrayList) edges.get(e.from);
else {
tmp = new ArrayList();
edges.put(e.from,tmp);
}
tmp.add(e);//adding an edge to tmp
later in the code you get the ArrayList out of the Map as ArrayList but it an ArrayList containing Edge
try to change
tmp = new ArrayList();
to
tmp = new ArrayList<Integer>();
you should get a compilation error when adding an Edge to it
You declare:
int from;
int to;
int type;
and you should declare them as Integers instead:
Integer from;
Integer to;
Integer type;
because later on you're doing:
this.from = new Integer(from);
etc.
A better option would be to change the assignment to:
this.from = from;
which would also solve this error since you would be assigning an int to an int. Is there a purpose you're using new Integer() ? because if not - I would suggest removing it - it's slower (performance-wise) comparing to the primitive int.
Bottom line: stay consistent and either use int throughout the code, or Integer - try not to mix them unless it's really required.
public ArrayList<Integer> getOutEdgesToP(int id) {
if (!edges.containsKey(id)) {
return null;
}
System.out.println(edges.get(id));
ArrayList<Integer> a = edges.get(id);
System.out.println("Arraylist a: " + a); // if i print using this its
// okay. but i cant get each
// item in this ArrayList like
// below
for (Object item : a) { // the error of classcastexception is here
System.out.println(item);
}
return a;
}
This should work. I don't have a lot of time to search for an explanation.
My Xml Should look like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<results>
<version>1.0</version>
<status>ok</status>
<lastUpdate>2011-11-21 09:23:59.0</lastUpdate>
<total>2</total>
<row>
<areaId></areaId>
<nameEng></nameEng>
<nameGer></nameGer>
</row>
… more <row></row> blocks …
</results>
How can i achieve this..?
At the moment i have the following.. but i dont know how i can return the album2 to the outputstream as a String...
List<Row> rows = new ArrayList<Row>();
while(rs.next()){
int albumId = rs.getInt(1);
int bookDocId = rs.getInt(2);
String picUrl = rs.getString(3);
String descEng = rs.getString(4);
String descGer = rs.getString(5);
Row row = new Row();
row.setAlbumId(albumId);
row.setBookDocId(bookDocId);
row.setPicUrl(picUrl);
row.setDescEng(descEng);
row.setDescGer(descGer);
rows.add(row);
}
Album album = new Album();
album.setRows(rows);
File file = new File("album.xml");
JAXB.marshal(album, file);
Album album2 = JAXB.unmarshal(file, Album.class);
file.deleteOnExit();
EDIT:
#XmlRootElement
public class Album {
private List<Row> rows = new ArrayList<Row>();
#XmlElement(name="row")
public List<Row> getRows(){
return this.rows;
}
public void setRows(List<Row> rows){
this.rows = rows;
}
Row.class:
public class Row {
private int albumId;
private int bookDocId;
private String picUrl;
private String descEng;
private String descGer;
public int getAlbumId() {
return albumId;
}
public int getBookDocId() {
return bookDocId;
}
public String getPicUrl() {
return picUrl;
}
public String getDescEng() {
return descEng;
}
public String getDescGer() {
return descGer;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public void setBookDocId(int bookDocId) {
this.bookDocId = bookDocId;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public void setDescEng(String descEng) {
this.descEng = descEng;
}
public void setDescGer(String descGer) {
this.descGer = descGer;
}
}
}
This is my code, it works well
#javax.xml.bind.annotation.XmlType
#javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
public class Album
{
long version;
String status;
java.util.List<Row> rows;
}
#javax.xml.bind.annotation.XmlType
#javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
public class Row
{
String areaId;
String nameEng;
String nameGer;
}
Test
public static void main(final String[] args) throws IOException
{
Album al = new Album();
List<Row> rows = new ArrayList<Row>();
final Row row1 = new Row();
row1.areaId = "area1";
row1.nameEng = "eng1";
row1.nameGer = "ger1";
final Row row2 = new Row();
row2.areaId = "area2";
row2.nameEng = "eng2";
row2.nameGer = "ger2";
rows.add(row2);
rows.add(row1);
al.status = "stat";
al.rows = rows;
final File file = new File("D:/test.xml");
final FileOutputStream out = new FileOutputStream(file);
JAXB.marshal(al, out);
final Album after = JAXB.unmarshal(file, Album.class);
assert after.status.equals(al.status);
assert after.rows.size() == al.rows.size();
}
You can change access to private and add getters, setters
To return like String use
ByteArrayOutputStream output = new ByteArrayOutputStream();
JAXB.marshal(al, output);
output.toString();
If you're asking how to write an Album to an output stream rather than write it to a file, then the answer is simple: JAXB.marshal(Object, OutputStream).
If you're asking how to transform an Album into an XML string, then the answer is also simple: JAXB.marshal(Object, String).
If you're asking something else, please clarify your question.