I have a class Player that has three variables, one of these is a List<List<Box>> and of course class Box does implement Serializable.
Box has some variables too, all of them are primitive types except for a class Dice which does implement Serializable too.
I have to send this class through the network with a socket and when I send this to the Client side the List<List<Box>> looks ok, and each Box too, the problem is that the Dice class that should be in the Box is always set to null even if the one I sent to the Client from the Server is not and I am absolutely sure that the network part is correct.
Forgot to mention that List<List<Box>> when instantiated becomes an ArrayList<ArrayList<Box>> which should be Serializable.
Dice class:
package ingsw.model;
import java.io.Serializable;
import java.util.Random;
public class Dice implements Serializable {
private int faceUpValue;
private final Color diceColor;
public Dice(Color diceColor) {
this.diceColor = diceColor;
}
public Dice(int faceUpValue, Color diceColor) {
this.faceUpValue = faceUpValue;
this.diceColor = diceColor;
}
/**
* Draft the dice
* get a random number between 1 and 6 and set the faceUpValue
*/
void roll() {
int value = (new Random()).nextInt(6) + 1;
setFaceUpValue(value);
}
public int getFaceUpValue() {
return faceUpValue;
}
public void setFaceUpValue(int faceUpValue) {
this.faceUpValue = faceUpValue;
}
public Color getDiceColor() {
return diceColor;
}
#Override
public String toString() {
if (faceUpValue != 0) {
return diceColor.toString() + String.valueOf(faceUpValue);
} else {
return diceColor.toString();
}
}
}
Card class implements Serializable:
public abstract class PatternCard extends Card {
private int difficulty;
protected List<List<Box>> grid;
public PatternCard(String name, int difficulty) {
super(name);
fillGrid();
this.difficulty = difficulty;
}
#Override
public String toString() {
return "PatternCard{" +
"'" + getName() + "'" +
'}';
}
public int getDifficulty() {
return difficulty;
}
public void setGrid(List<List<Box>> grid) {
this.grid = grid;
}
public List<List<Box>> getGrid() {
return grid;
}
private void fillGrid() {
this.grid = new ArrayList<>(4);
this.grid.add(new ArrayList<>(5));
this.grid.add(new ArrayList<>(5));
this.grid.add(new ArrayList<>(5));
this.grid.add(new ArrayList<>(5));
}
}
Box class:
public class Box implements Serializable {
private Color color;
private Integer value;
private Dice dice;
public Box(Color color) {
this.color = color;
}
public Box(Integer value) {
this.value = value;
}
public Color getColor() {
return color;
}
public Integer getValue() {
return value;
}
public boolean isValueSet() {
return value != null;
}
public void insertDice(Dice dice) {
this.dice = dice;
//TODO the dice at this point must removed from the dice drafted --> dices (set).remove();
}
public void removeDice() {
if (dice != null) dice = null;
//TODO dice must be re-added?
}
public Dice getDice() {
return dice;
}
#Override
public String toString() {
if (isValueSet()) return String.valueOf(value);
else return color.toString();
}
Boolean isDiceSet(){ return dice != null; }
}
I've investigated a bit and thought that I should probably Serialize the object and De-serialize it by myself but I don't know if that could be the real issue here since ArrayLists are Serializable and every object inluded in these ArrayLists are too.
What could possibly be wrong in this?
Related
I have three classes called League, Team and Player, League has an array with teams, and I have a method called showLeagueTable that shows team sorted by ranking(which is a method that exists in the Team class) and the class Team has an array of players.
League.java
public class League<T extends Team> {
public String name;
private List<T> teams = new ArrayList<>();
public League(String name) {
this.name = name;
}
public boolean add(T team) {
if (teams.contains(team)) {
return false;
}
return teams.add(team);
}
public void showLeagueTable() {
Collections.sort(this.teams);
for (T t: teams) {
System.out.println(t.getName() + ": " + t.ranking());
}
}
}
Team.java
public class Team<T extends Player> implements Comparable<Team<T>> {
private String name;
int played = 0;
int won = 0;
int lost = 0;
int tied = 0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean addPlayer(T player) {
if (members.contains(player)) {
System.out.println(player.getName() + " is already on this team");
return false;
} else {
members.add(player);
System.out.println(player.getName() + " picked for team " + this.name);
return true;
}
}
public int numPlayers() {
return this.members.size();
}
public void matchResult(Team<T> opponent, int ourScore, int theirScore) {
String message;
if (ourScore > theirScore) {
won++;
message = " beat ";
} else if (ourScore == theirScore) {
tied++;
message = " drew with ";
} else {
lost++;
message = " lost to ";
}
played++;
if (opponent != null) {
System.out.println(this.getName() + message + opponent.getName());
opponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking() {
return (won * 2) + tied;
}
#Override
public int compareTo(Team<T> team) {
return Integer.compare(team.ranking(), this.ranking());
}
}
Player.java
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
but in the line Collections.sort(this.teams); from the class League, I got the warning Unchecked method 'sort(List<T>)' invocation, I have read that maybe the problems is that I haven't implemented the Comparable interface in my class Team with a Type, but I did it you can see it at the line:
public class Team<T extends Player> implements Comparable<Team<T>>
can someone help me, please, thanks!
here a fully workable code for you specific issue :
it removes warning and errors.
phase 1 : remove comparable behaviour
phase 2 : try to compile without warning
phase 3 : try with a real new allocation : imporant, because, if you do not do anything new, T generics are not used, and you can not detect errors.
phase 4 : adding comparable behaviour.
final source [ see A) B) and C) mistakes in source]
League.java
package test;
import java.util.ArrayList;
import java.util.List;
import test.Team;
import java.util.Collections;
// -- A) missing precision about Team , Team based on Player
// -- public class League<T extends Team>
public class League<T extends Team<E>, E extends Player>
{
public String name;
// B) ! miss <T> after new :
// private List<T> teams = new ArrayList<>();
private List<T> teams = new ArrayList<T>();
public League(String name) {
this.name = name;
}
public boolean add(T team) {
if (teams.contains(team)) {
return false;
}
return teams.add(team);
}
public void showLeagueTable() {
Collections.sort(this.teams);
for (T t: teams) {
System.out.println(t.getName() + ": " + t.ranking());
}
}
}
Team.java
package test;
import java.util.ArrayList;
public class Team<T extends Player> implements Comparable<Team<T>> {
private String name;
int played = 0;
int won = 0;
int lost = 0;
int tied = 0;
// C) !! MISS <T> after new ArrayList
// private ArrayList<T> members = new ArrayList<>();
private ArrayList<T> members = new ArrayList<T>();
#Override
public int compareTo(Team<T> team) {
return Integer.compare(team.ranking(), this.ranking());
}
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean addPlayer(T player) {
if (members.contains(player)) {
System.out.println(player.getName() + " is already on this team");
return false;
} else {
members.add(player);
System.out.println(player.getName() + " picked for team " + this.name);
return true;
}
}
public int numPlayers() {
return this.members.size();
}
public void showPlayers() {
for (T element : members) {
System.out.println(element.getName());
}
}
public void matchResult(Team<T> opponent, int ourScore, int theirScore) {
String message;
if (ourScore > theirScore) {
won++;
message = " beat ";
} else if (ourScore == theirScore) {
tied++;
message = " drew with ";
} else {
lost++;
message = " lost to ";
}
played++;
if (opponent != null) {
System.out.println(this.getName() + message + opponent.getName());
opponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking() {
return (won * 2) + tied;
}
}
Player.java
package test;
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Test.java
package test;
import test.League;
import test.Team;
import test.Player;
public class Test {
Player p1;
Player p2;
Player p3;
Player p4;
Player p5;
Player p6;
Player p7;
Player p8;
Player p9;
Team<Player> t1;
Team<Player> t2;
Team<Player> t3;
Team<Player> t4;
public void test() {
System.out.println("RUNNING TEST");
p1=new Player("Mike");
p2=new Player("John");
p3=new Player("Jenny");
p4=new Player("Sunny");
p5=new Player("Mike");
p6=new Player("Jeremy");
p7=new Player("Gwen");
p8=new Player("Hector");
p9=new Player("Henry");
t1=new Team<Player>("Team1");
t2=new Team<Player>("Team2");
t3=new Team<Player>("Team3");
t4=new Team<Player>("Team4");
t1.addPlayer(p1);
t1.addPlayer(p2);
t2.addPlayer(p3);
t2.addPlayer(p4);
t2.addPlayer(p5);
t3.addPlayer(p6);
t3.addPlayer(p7);
t4.addPlayer(p8);
t4.addPlayer(p9);
// test show players
t1.showPlayers();
System.out.println("------------");
System.out.println("num players in team is "+t1.numPlayers());
System.out.println("---adding team in league ---------");
League<Team<Player>, Player> g1=new League<Team<Player>, Player>("League 1");
g1.add(t1);
g1.add(t2);
League<Team<Player>, Player> g2=new League<Team<Player>, Player>("League 2");
g2.add(t3);
g2.add(t4);
System.out.println("---settings results ---------");
t1.matchResult(t2, 2, 8);
t2.matchResult(t1, 1, 7);
t3.matchResult(t4, 4, 5);
t3.matchResult(t4, 4, 0);
System.out.println("-----League 1---------");
g1.showLeagueTable();
System.out.println("-----League 2---------");
g2.showLeagueTable();
}
}
Main.java
import test.Test;
public class Main
{
public static void main(String[] args) {
System.out.println("running MAIn");
Test test = new Test();
test.test();
}
}
Here is the Goals.java
public abstract class Goals {
private String score;
public Goals(String str) {
this.score = str;
}
String getGoals() {
return this.score;
}
void doSomething(score) {
}
}
Here is the Game.java
public class Game implements Serializable {
public String name;
public int game_num;
public int opp;
public int player;
public Goals goal;
public Game(int i, int i2, int i3) {
this.player = i;
this.game_num = i2;
this.opp = i3;
}
public Game(String str, Goals goal) {
this.name = str;
this.goal = goal;
}
}
Can we create a Serialized Object in a way that after it is deserialized and casted to Game , it will set score inside Goals.java ?
Also, can you manipulate / overwrite doSomething method if the serialized data comes from untrusted source?
In the way you are trying to manipulates your objects, I think you can do that Goals implements Serializable, and Game implements Goals:
public abstract class Goals implements Serializable{
private String score;
public Goals(String str) {
this.score = str;
}
String getGoals() {
return this.score;
}
void doSomething(score) {
}
}
for Game
public class Game extends Goals {
public String name;
public int game_num;
public int opp;
public int player;
public Game(int i, int i2, int i3) {
this.player = i;
this.game_num = i2;
this.opp = i3;
}
public Game(String str) {
//create constructor also including the properties of Goals
Super()...
}
}
As mentioned in comments, implement Goals and its implementation with Serializable and also implement default constructor in both the classes .
Working piece of code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
abstract class Goals implements Serializable{
private String score;
public Goals() {
this(null);
}
public Goals(String str) {
this.score = str;
}
String getGoals() {
return this.score;
}
void doSomething(int score) {
}
}
class Game implements Serializable {
public String name;
public int game_num;
public int opp;
public int player;
public Goals goal;
public Game(int i, int i2, int i3) {
this.player = i;
this.game_num = i2;
this.opp = i3;
}
public Game(String str, Goals goal) {
this.name = str;
this.goal = goal;
}
}
class GoalImpl extends Goals implements Serializable{
public GoalImpl() {
}
public GoalImpl(String str) {
super(str);
}
}
public class Main{
public static void main(String...s) {
Goals goal = new GoalImpl("20");
Game game = new Game("name",goal);
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream("gamefile.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of object
out.writeObject(game);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch(IOException ex)
{
ex.printStackTrace();
System.out.println("IOException is caught");
}
Game object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream("gamefile.ser");
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
object1 = (Game)in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized ");
System.out.println("score = " + object1.goal.getGoals());
}
catch(IOException ex)
{
ex.printStackTrace();
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Output:
Object has been serialized
Object has been deserialized
score = 20
PS:
An advice to make score as integer as otherwise you will not be able to do basic operations like increase score or decrease score using inbuilt operators (+ , - )
Always place proper getter setter name like getScore() and setScore int this case.
Do try to make constructors in sync, for example in case of Game constructor with player id, game num and opposition is called, Game name and Goals will never be initialized, better to initialize them with default value or other good option is make another constructor accepting all parameters and then from individual constructos you can call master constructor and pass default values for those which are not passed by the calling method.
I have got an array of 20:
private Karte[] deckArr;
deckArr = new Karte[20];
Now I want to sort the array by card-names every time a new card is added.
P.S. the cards are added 1 by 1 after clicking on a button, so there are empty spaces in the array.
Since the...
Arrays.sort(deckArr.getName());
...method does not work here I asked myself how it is done.
Karte(card) class:
package Model;
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements ComparableContent<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
#Override
public boolean isLess(Karte karte) {
if (getName().compareTo(karte.getName()) < 0){
return true;
}else{
return false;
}
}
#Override
public boolean isEqual(Karte karte) {
return getName() == karte.getName();
}
#Override
public boolean isGreater(Karte karte) {
if (getName().compareTo(karte.getName()) > 0){
return true;
}else{
return false;
}
}
}
Any help is appreciated!
Why not just use ArrayList instead? Easier to add, remove elements and you will never have empty slots.
Anyway to sort you can use Collections.sort like this:
deckArr = new ArrayList<Karte>();
Collections.sort(deckArr, Comparator.comparing(karte -> karte.getName()));
Java 8 offers a simple solution:
The Comparable Interface has a static method that creates a Comaprator with an extractor.
Comparator<Card> comp = Comparator.comparing(Karte::getName);
With this using a sorting method (e.g. Arrays.sort) is easy to call.
On top of that, to solve your nullpointer problem, the Comparator Interface offers another two functions: NullsLast and nullsFirst.
Comparator<Card> comp = Comparator.nullsLast(Comparator.comparing(Card::getName));
For me this looks like the easiest solution to your question :)
This should solve your problem. Implements the Comparable interface.
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements Comparable<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
public int compareTo(Karte karte) {
return this.name.compareTo(karte.getName());
}
}
Then you just need to call Arrays.sort(deckArr);
You need to check for nulls and just call below--
Arrays.sort(deckArr, new Comparator<Karte>() {
#Override
public int compare(Karte karte1, Karte karte2) {
if (karte1.getName() == null && karte2.getName() == null) {
return 0;
}
if (karte1.getName() == null) {
return 1;
}
if (karte2.getName() == null) {
return -1;
}
return karte1.getName().compareTo(karte2.getName());
}});
Good Day,
I am writing a custom event handler in Java. I have a class called BoogieCarMain.java that instantiates three instances of a type called BoogieCar. Whenever any of the three instances exceeds a certain speed limit, then an event should be fired off. The code I currently have is working, so here is what I have:
// BoogieCar.java
import java.util.ArrayList;
public class BoogieCar {
private boolean isSpeeding = false;
private int maxSpeed;
private int currentSpeed;
private String color;
BoogieSpeedListener defaultListener;
public BoogieCar(int max, int cur, String color) {
this.maxSpeed = max;
this.currentSpeed = cur;
this.color = color;
}
public synchronized void addSpeedListener(BoogieSpeedListener listener) {
defaultListener = listener;
}
public void speedUp(int increment) {
currentSpeed += increment;
if (currentSpeed > maxSpeed) {
processSpeedEvent(new BoogieSpeedEvent(maxSpeed, currentSpeed, color));
isSpeeding = true;
} else {
isSpeeding = false;
}
}
public boolean getSpeedingStatus() {
return isSpeeding;
}
private void processSpeedEvent(BoogieSpeedEvent speedEvent) {
defaultListener.speedExceeded(speedEvent);
}
}
// BoogieCarMain.java
import java.util.ArrayList;
public class BoogieCarMain {
public static void main(String[] args) {
BoogieCar myCar = new BoogieCar(60, 50, "green");
BoogieCar myCar2 = new BoogieCar(75, 60, "blue");
BoogieCar myCar3 = new BoogieCar(65, 25, "pink");
BoogieSpeedListener listener = new MySpeedListener();
myCar.addSpeedListener(listener);
myCar2.addSpeedListener(listener);
myCar3.addSpeedListener(listener);
myCar.speedUp(50); // fires SpeedEvent
System.out.println(myCar.getSpeedingStatus());
myCar2.speedUp(20);
System.out.println(myCar2.getSpeedingStatus());
myCar3.speedUp(39);
System.out.println(myCar3.getSpeedingStatus());
}
}
// BoogieSpeedListener.java
public interface BoogieSpeedListener { // extends java.util.EventListener
public void speedExceeded(BoogieSpeedEvent e);
}
// MySpeedListener.java
public class MySpeedListener implements BoogieSpeedListener {
#Override
public void speedExceeded(BoogieSpeedEvent e) {
if (e.getCurrentSpeed() > e.getMaxSpeed()) {
System.out.println("Alert! The " + e.getColor() + " car exceeded the max speed: " + e.getMaxSpeed() + " MPH.");
}
}
}
// BoogieSpeedEvent.java
public class BoogieSpeedEvent { // extends java.util.EventObject
private int maxSpeed;
private int currentSpeed;
private String color;
public BoogieSpeedEvent(int maxSpeed, int currentSpeed, String color) {
// public SpeedEvent(Object source, int maxSpeed, int minSpeed, int currentSpeed) {
// super(source);
this.maxSpeed = maxSpeed;
this.currentSpeed = currentSpeed;
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public int getCurrentSpeed() {
return currentSpeed;
}
public String getColor() {
return color;
}
}
My question is: While this code works, I would like the BoogieCar type to notify BoogieCarMain directly without me have to "poll" the BoogieCar type by having to invoke the getSpeedingStatus() method.
In other words, perhaps defining a variable in BoogieCarMain.java that changes whenever one of the three cars exceeds its predefined speed limit. Is it possible to have the BoogieCar type set the variable?
Is there a cleaner way to do this?
TIA,
coson
Callbacks are ideal for this scenario.
// BoogieCarMain provides a sink for event-related information
public void handleSpeeding(BoogieCar car) {
System.out.println(car.getSpeedingStatus());
}
// MySpeedListener knows about an object that wants event-related information.
// I've used the constructor but an addEventSink method or similar is probably better.
public MySpeedListener(BoogieCarMain eventSink) {
this.eventSink = eventSink;
}
// MySpeedListener handles events, including informing objects that want related information.
// You decide if the event is an appropriate type for the sink to know about.
// Often it isn't, and instead your listener should pull the relevant info out of the event and pass it to the sink.
public void speedExceeded(BoogieSpeedEvent e) {
if (e.getCurrentSpeed() > e.getMaxSpeed()) {
// I've taken the liberty of adding the event source as a member of the event.
eventSink.handleSpeeding(e.getCar());
}
}
I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.