Can anyone tell me why this method is throwing an unchecked or unsafe exception? I understood that to happen when I try to edit the list I am iterating through... in the below, currentAdvanceTactics etc are not being iterated through at all.
public void tacticMeetsRequirements(ArrayList<Tactics> master) {
for (Tactics a : master) {
if (meetsrequirements(a)) {
if (a.movement.equals("Advance")) {
currentAdvanceTactics.add(a);
} else if (a.movement.equals("Retreat")) {
currentRetreatTactics.add(a);
} else if (a.movement.equals("Guard")) {
currentGuardTactics.add(a);
}
}
}
}
This is how the objects used in the master list are created:
for (int b = 0; b < numberoftactics; b++) {
tactic[b] = new Tactics(parsedTactics[b]);
tacticsMaster.add(tactic[b]);
}
parsedTactics is just raw data which gets read into the different variables.
tacticsMaster is declared as such:
public ArrayList<Tactics> tacticsMaster;
then later when I create the object it is contained within:
this.tacticsMaster = new ArrayList<Tactics>();
The currentAdvanceTactics list etc are all created as such:
public ArrayList currentGuardTactics = new ArrayList<Tactics>();
public ArrayList currentAdvanceTactics = new ArrayList<Tactics>();
public ArrayList currentRetreatTactics = new ArrayList<Tactics>();
Thanks in advance for any help!
You are using the raw version of the generic-type (ArrayList<T>). That's why you get the warning.
public ArrayList currentGuardTactics = new ArrayList<Tactics>();
public ArrayList currentAdvanceTactics = new ArrayList<Tactics>();
public ArrayList currentRetreatTactics = new ArrayList<Tactics>();
Try using the parameterized version -
public List<Tactics> currentGuardTactics = new ArrayList<Tactics>();
public List<Tactics> currentAdvanceTactics = new ArrayList<Tactics>();
public List<Tactics> currentRetreatTactics = new ArrayList<Tactics>();
The declaration of your ArrayLists are not type-safe. Change it to:
private ArrayList<Tactics> currentGuardTactics = new ArrayList<Tactics>();
private ArrayList<Tactics> currentAdvanceTactics = new ArrayList<Tactics>();
private ArrayList<Tactics> currentRetreatTactics = new ArrayList<Tactics>()
You should make the members also private. public declarations are usually not the best-practice way.
Related
I've defined a arrayList as following
List<List<RiskyPersons>> dataArray = new ArrayList<>();
Here is RiskyPersons Class
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
Then I've successfully added data and saved in dataArray ArrayList.
Following output is showing the saved ArrayList using SOP(dataArray);
[[RiskyPersons{sa3tenant=Homeless.SA3Tenant#3a7cc6b0, NumberofPersonInCategory=99}]]
I want to read this dataArray ArrayList and display values separately. How do I access "NumberofPersonInCategory" value?
From Java-8 and above one can use stream:
dataArray.stream()
.flatMap(List::stream)
.map(RiskyPersons::NumberofPersonInCategory)
.forEach(System.out::println)
I hope this will help you !
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public int getNumberofPersonInCategory() {
return NumberofPersonInCategory;
}
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
List<Integer> values = dataArray.parallelStream().flatMap(Collection::stream).map(RiskyPersons::getNumberofPersonInCategory)
.collect(Collectors.toCollection(ArrayList::new));
You'll need to iterate it twice as
for (List<RiskyPersons> rp : dataArray) {
for (RiskyPersons o : rp) {
System.out.println(o.NumberofPersonInCategory); // unrelated : but its bad naming convention
}
}
I am currently trying to add a value to an ArrayList object from a method inside of another class.
Here is the class I have created for the ArrayList Object:
public class ArrayClass {
public static ArrayList<String> array = new ArrayList<>();
public static void add_val(String s){
array.add(s);
}
public static int get_size(){
return array.size();
}
public static String get_val(int i){
return array.get(i);
}
}
And the other class where I attempt to edit the ArrayList object:
ArrayClass fill = new ArrayClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
Response.Listener<String> responseListener4 = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse4 = new JSONObject(response);
boolean success = jsonResponse4.getBoolean("success");
if (success){
int l;
String filled;
int length4 = jsonResponse4.length();
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.add_val(filled);
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(ExploreActivity.this);
builder.setMessage("Could not retrieve restaurant tables filled")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
FilledRequest filledRequest = new FilledRequest(responseListener4);
RequestQueue queue4 = Volley.newRequestQueue(ExploreActivity.this);
queue4.add(filledRequest);
If you look in the onResponse method, you can see the attempt to add a value from the jsonResponse into the ArrayClass object. However, when I launch my app, it does not add the value into the object. I'm used to python global variables and not having to deal with the semantics of java, so if you could shed some light on what changes need to be made, I would greatly appreciate it.
Apart from other given answers/solutions to the issue you are facing, let me share a best and optimized way to implement JSON parsing in Android.
I would suggest you to check GSON or Jackson libraries which provides Java serialization/deserialization that can convert Java Objects into JSON and back.
There are some benefits it does provide, one of the main benefits is you do not need to implement parsing manually and less chances of mistakes in implementing parsing, like you may make a mistake in mentioning key "Success" or "success" or any such silly mistakes!
Firstly, since your variable is static, and the methods are static too, you don't have to instantiate the object. You could do something like this:
ArrayClass.add_val("Hello");
But if you want to instantiate then you can do this:
public class ArrayClass {
private ArrayList<String> array;
public ArrayClass() {
array = new ArrayList<>();
}
public void add_val(String s){
array.add(s);
}
public int get_size(){
return array.size();
}
public String get_val(int i){
return array.get(i);
}
}
To make sure the values are filled in, you can check the array size like this:
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.add_val(filled);
}
Log.d("TEST", String.valueOf(fill.get_size());
Remove all cases of the static keyword in ArrayClass. Static methods are class level methods, ie. are called on the class itself, rather than an instance of the class.
You can also try this, for ArrayList:
First do some changes in your ArrayClass. Use get And Set method to access your array.
public class ArrayClass {
private ArrayList<String> array = new ArrayList<>();
public ArrayList<String> getArray() {
return array;
}
public void setArray(ArrayList<String> array) {
this.array = array;
}
}
And your other class where you attempt to edit the ArrayList use getArray And SetArray method and some predefined method of ArrayList like this:
Store the data in ArrayList:
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.getArray().add(filled);
}
Get Size of ArrayList:
fill.getArray().size();
And also you can store an another ArrayList like
ArrayList<String> tempArrayList = new ArrayList<String>();
tempArrayList.add("string 1");
tempArrayList.add("string 2");
tempArrayList.add("string 3");
tempArrayList.add("string 4");
fill.setArray(tempArrayList)
I have two classes. One that has the array (ArrayStorage) and the other (ArrayConsumer) has just a variable that will act as a simple reference to an array.
I add a new element to the array using $my_array. Then I check to see if the new element is visible in the $obtained_array. But the test fails because it cannot find the new element. They act like they were different arrays. Shouldn't they point to the same array?
public function testArrayMadness() {
$arrayStorage = new ArrayStorage();
$my_array = $arrayStorage->getArray();
$arrayConsumer = new ArrayConsumer($my_array);
$obtained_array = $arrayConsumer->getArray();
$my_array[3]='c';
$this->assertContains('c', $obtained_array);
}
}
class ArrayStorage {
private $my_array=[1=>'a',2=>'b'];
function getArray() { return $this->my_array; }
}
class ArrayConsumer {
private $obtained_array;
function __construct($array) { $this->obtained_array=$array; }
function getArray() { return $this->obtained_array; }
}
Update:
I did the same on test in Java, it gives me an indexOutOfBoundsException. Does that mean both php and java works the same way in this aspect or is there something wrong with my code?
#Test
public void testArrayMadness() {
ArrayStorage arrayStorage = new ArrayStorage();
List<String> my_list = arrayStorage.getList();
ArrayConsumer arrayConsumer = new ArrayConsumer(my_list);
List<String> obtained_array = arrayConsumer.getList();
my_list.add("c");
assertEquals("c", obtained_array.get(3));
}
}
class ArrayStorage {
private List<String> my_list;
public ArrayStorage() {
my_list = new ArrayList<>();
my_list.add("a");
my_list.add("b");
}
public List<String> getList() { return my_list; }
}
class ArrayConsumer {
private List<String> obtained_list;
public ArrayConsumer(List<String> list) {
this.obtained_list = list;
}
public List<String> getList() { return this.obtained_list; }
}
PHP arrays are not objects, they are assigned by value:
$a = [1,2,3];
$b = $a;
$b[2] = 99;
print_r($b); // 1,2,99
print_r($a); // 1,2,3
A workaround is to use reference signs & (a bad idea generally) or ArrayObjects:
$a = new ArrayObject([1,2,3]);
$b = $a;
$b[2] = 99;
print_r($b); // 1,2,99
print_r($a); // 1,2,99
return reference array using & operator
something like return &$this->my_array;
I'm trying to create two objects of a Silo class in a SiloManager class, so that I can access both objects' methods. But I can't seem to make the SiloManager constructor work, nor to instance the classes properly. (I'm a beginner in java). Here's my code:
public class GrainSiloManager {
public GrainSilo silo1 = new GrainSilo(100);
public GrainSilo silo2 = new GrainSilo(50);
public GrainSiloManager(GrainSilo silo1, GrainSilo silo2) {
this.silo1 = silo1;
this.silo2 = silo2;
}
private void showStatus() {
System.out.println("The current grain in silo1 is: " + silo1.getGrain());
System.out.println("The current grain in silo2 is: " + silo2.getGrain());
}
}
As I say i'm a beginnger so go easy heh, thanks for any help.
public GrainSilo silo1 = new GrainSilo(100);
public GrainSilo silo2 = new GrainSilo(50);
public GrainSiloManager(GrainSilo silo1, GrainSilo silo2) {
this.silo1 = silo1;
this.silo2 = silo2;
}
This will get compiled as:
public GrainSilo silo1;
public GrainSilo silo2;
public GrainSiloManager(GrainSilo silo1, GrainSilo silo2) {
this.silo1 = new GrainSilo(100);
this.silo2 = new GrainSilo(50);
this.silo1 = silo1;
this.silo2 = silo2;
}
which as you can see makes little to no sense. You're overwriting the object that you make, with the objects passed into the constructor.
Your constructor is going to replace the "public!" silo1 and silo2 objects with whatever is passed in. You could change your constructor like this
public GrainSiloManager() {
super();
}
or the even shorter (but equivalent)
public GrainSiloManager() {
}
And then call it like this
new GrainSiloManager().showStatus();
or you can use your existing approach (which will replace the GrainSoloManager.silo1 and GrainSoloManager.silo2 in your constructor)
GrainSilo silo1 = new GrainSilo(100);
GrainSilo silo2 = new GrainSilo(50);
new GrainSiloManager(silo1, silo2).showStatus();
I need to create array of references to child objects. In this case Room has to have array of references to objects: DarkRoom and LightRoom. Having error in line where initialization of array of type Room. What's missing?
public abstract class Room {
public Room[][] space = new Room[4][4]; // <<Syntax error on token ";",
space[0][0] = new DarkRoom();
space[0][1] = new LightRoom();
space[1][0] = new DarkRoom();
space[1][1] = new LightRoom();
}
public class LightRoom extends Room { ... }
public class DarkRoom extends Room { ... }
Your design is way off the mark. A class should not hold an array of child objects and in fact should have no knowledge about or dependence on its child classes. This is both a recursive and a logical nightmare.
I suggest you remove the array from within the Room class to somewhere more appropriate, such as the Hotel class or House class.
The initialization should not be done outside an initialization block or method, instead, do:
public Room[][] space = new Room[4][4];
{
space[0][0] = new DarkRoom();
space[0][1] = new LightRoom();
space[1][0] = new DarkRoom();
space[1][1] = new LightRoom();
}
It's complaining about the space[][] blocks. You can't just write code into your class definition.
public abstract class Room {
public Room[][] space = new Room[4][4]; // << error Syntax error on token ";",
public Room()
{
space[0][0] = new DarkRoom();
space[0][1] = new LightRoom();
space[1][0] = new DarkRoom();
space[1][1] = new LightRoom();
}
}