This question already has answers here:
Add ArrayList to another ArrayList in java
(6 answers)
Closed 7 years ago.
I'm writing a class called List which creates an instance variable array of Customers (Customer is just another class that accepts String parameters for a person's name),
i.e private Customer[] data
I'm trying to write an append method that will take a Customer and add it to another List in the main method.
To do this, there seems to be a method called addAll(), but since I'm writing this code by scratch, I can't use this. I looked at the pseudo code though for this method to get a general idea and it converts the Object into an array and then uses arraycopy to append the two lists.
I meant to say, this way makes sense to me, if I were using arrays, but I'm trying to add a Customer object from another list and add them to a list in the main method.
Not sure of what you want, but I think you can implement the append method yourself just as what the arraycopy method do. Here is a simple example
class List {
private int size;
private Customer[] data;
private final static int DEFAULT_CAPACITY = 10;
public List() {
size = 0;
data = new Customer[DEFAULT_CAPACITY];
}
public void append(List another) {
int anotherSize = another.size;
for (int i = anotherSize - 1; i >= 0; --i) {
if (size < data.length) {
data[size++] = another.data[i];
another.data[i] = null;
another.size--;
} else {
throw new IndexOutOfBoundsException();
}
}
}
}
Related
So i am doing a first year university assignment question and i am going to be honest about it. I just want to make things clear before some of you come down-voting my question. I don't want complete code, i just want some help with a few things.
The question is divided into two parts. The first part is to write a Nucleotide class whose constructor has two properties. A single character called base that has to be either 'a' or 'c' or 'g' or 't' otherwise it should be 'n' and a boolean called degenerate.
My code for this part is here:
class Nucleotide {
private char base;
private boolean degenerate;
public nucleotide(char base, boolean degenerate){
if(base != ‘a’ || base != ‘c’ || base != ‘g’ || base != ’t’){
this.base = ’n’;
} else {
this.base = base;
}
this.degenerate = degenerate;
}
}
The next part of the question says to use the Nucleotide object and create a new Bacteria class. An instance of bacteria consists of a genome (a collection of nucleotides), and a species (a String).
You must create a constructor which accepts a String and a collection, and uses those to
initialize the species and the collection of nucleotides.
My code for this part is here:
class Bacteria {
//private ArrayList<Nucleotide> genome;
private String species;
public Bacteria(String species, ArrayList<Nucleotide> genome) {
genome = new ArrayList<Nucleotide>();
this.species = species;
}
My problem starts with the next step which asks us to write an instance method that performs deep copy and returns an instance of Bacteria.
public Bacteria binaryFission() {
How can i perform deep copy without serialization and reflection. I hardly know anything about those things.
Again i need pointers or the basic idea of how to go about completing the binaryFission() method. I have gone through several deep copy questions that are on SO but none of them are relevant to my question so i don't believe that i am asking a duplicate question. I am happy to provide more details though.
This is the way to do it manually
public Bacteria binaryFission() {
String speciesClone = this.species;
ArrayList<Nucleotide> genomeClone = new ArrayList<Nucleotide>();
//now iterate over the existing arraylist and clone each Nucleotide
for(int index = 0; index < this.genome.size(); index++)
{
genomeClone.add(new Nucleotide(
genome.get(index).getBase(), //needs to be added to the Nucleotide class to retrieve the base variable
genome.get(index).getDegenerate() //needs to be added to be allowed to get its degenerate
));
}
return new Bacteria(speciesClone, genomeClone);
}
FYI - you'll need to add getters for your Nucleotide class private variables in order for this to work since they are private and Bacteria won't have access to their values without them.
Since Nucleotide has no setters, and its fields are primitive, it is effectively immutable (can't be changed and therefore safe to "reuse"). You would be better to make the fields final to formally make it immutable.
All you need to make a deep copy is to make a shallow copy of your Nucleotide list and use that in your new Bacteria. You can make a copy like this:
List<Nucleotide> copy = new ArrayList<>(genome);
You could create a simple factory method on Bacteria that returns a deep copy of itself:
public Bacteria copy() {
return new Bacteria(species, new ArrayList<>(genome));
}
This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 6 years ago.
I have a program that creates a couple objects and adds each one to an ArrayList, then is supposed to loop over each object in the ArrayList and use a getter from another class within the project to display information on each object. I can't get the objects in my foreach loop to use any of the methods in my other class. Here is my main, including the trouble loop at the bottom:
import java.util.ArrayList;
public class ITECCourseManager {
public static void main(String[] args) {
ArrayList ITECCourse = new ArrayList();
ITECCourse infotech = new ITECCourse("Info Tech Concepts", 1100, 5, "T3050");
infotech.addStudent("Max");
infotech.addStudent("Nancy");
infotech.addStudent("Orson");
ITECCourse.add(infotech);
ITECCourse java = new ITECCourse("Java Programming", 2545, 3, "T3010");
java.addStudent("Alyssa");
java.addStudent("Hillary");
ITECCourse.add(java);
for (Object course : ITECCourse) {
System.out.println("Name: " + course.getName());
}
}
}
And here is the other class in my project with the method I need to use:
public class ITECCourse {
public String name;
public int code;
public ArrayList<String> students;
public int maxStudents;
public String room;
ITECCourse(String courseName, int courseCode, int courseMaxStudents, String roomNum) {
name = courseName;
code = courseCode;
maxStudents = courseMaxStudents;
students = new ArrayList<String>();
room = roomNum;
}
public String getName() {
return name;
}
If I replace course.getName() with java.getName(), the code works. I'm confused why I can't use a foreach loop across the ArrayList to use the getter for each object, when I am able to call the object and use the method directly from the same place in the code.
Edit: Thank you for the answers, simple mistake only had to make two/three changes: declare ArrayList<ITECCourse> at the beginning, change Object in for loop to ITECCourse, and of course change my arraylist from ITECCourse to ITECCourseList so there isn't confusion with my ITECCourse class.
The call to course.getName() doesn't work because you've defined course as an Object in your loop and Object doesn't have the method getName(). If you add a type parameter to your ArrayList declaration such as ArrayList<ITECCourse>, then you can iterate over the list of ITECCourse instances rather than Object.
On a side note, naming your variable ITECCourse will just lead to confusion because it's the same as your class. Might be better to name your variable something like itecCourseList.
I have been given a starting code to work on a project, however I am confused about the following code and cant seem to find any examples online!
public static Entity[][] read(){ ... }
How can I handle this Entity to add new entries to an array, and then how can I return this?
The following constructor is invoked by a different class.
public World() {
aWorld = new Entity[SIZE][SIZE];
int r;
int c;
for (r = 0; r < SIZE; r++) {
for (c = 0; c < SIZE; c++) {
aWorld[r][c] = null;
}
}
aWorld = FileInitialization.read();
}
I feel it would be much simpler if the array was just a parameter or if it were something like:
public static int[][] read(){ ... }
UPDATE:
The goal is to read from a file in the method read() and then assign the an entity to the correct location based on the location in the file. But I am not able to assign since the data types would be incompatible, Required is Entity, but I want to be able to set it to an int, char or String.
To add to an array of objects, you do exactly what you would with an array of primitives (e.g. ints), you just use Entitys. So if you want to add something to aWorld you use
aWorld[r][c] = new Entity(...); //with provided constructor's parameters
// or
aWorld[r][c] = existing_Entity; //for an Entity variable you already have
When you're done adding, you simply return the array aWorld.
If FileInitialization's static read() is going to return Entity[][], that's an entity array by itself. It means that you shouldn't iterate aWorld, rather assign the return value to it directly like
aWorld = FileInitialization.read();
Inside the read(), use that for loop you've made in the constructor and add a new Entity object as noted by Linus
Alright I would like to say thanks to all of you here as I was set on the right direction. But I would like to share my answer which should be simple and hopefully make someones life easier in the future.
To initialize the array of objects just do it as you would initialize any other array, in this case:
Entity[][] reference_name = new Entity[SIZE][SIZE];
To return this value, simply return the reference:
return reference_name;
Now the part where you actually modify an entry into your array.
Lets say you have something like
public static void Entity[][] read() { .. }
you need to create a class file Entity.java (same name as the array type being passed)
In this case it would look something like this:
public class Entity {
private char appearance;
public Entity(char anAppearance) {
appearance = anAppearance;
}
now to give this array an entry do something like this:
reference_name[0][0] = new Entity('X');
alright and in case you are wondering how to display this just add an accesor method to class Entity.
public char getAppearance() {
return(appearance);
}
and to output:
System.out.println(reference_name[0][0].getAppearance(); );
I am not sure how to describe this in title, I am a beginner of Java, here is a little sample code:
My target is similar to this question: Union of two object bags in Java, the difference is in the parameter, the solution provided in this question has a T[] item, in my case, it is BagInterface<T> anotherBag
Interface: http://people.cs.pitt.edu/~ramirez/cs445/handouts/BagInterface.java
ArrayBag.java: in union(), I wish to add all items up in the 2 bags (sets of data) to 1.
public class ArrayBag<T> implements BagInterface<T>
{
private int length;
...
/* union of 2 bags */
public BagInterface<T> union(BagInterface<T> anotherBag) // This has to be stay like that.
{
int total = length + anotherBag.getSize();
BagInterface<T> items = (T[]) new Object[total]; // this may be faulty
for (int i = 0; i < length; i++)
items.add(bag[i]); // bag is current bag
for (int i = 0; i < anotherBag.getSize(); i++) // this is definitely wrong
items.add(anotherBag[i]);
return items;
}
}
What can I do to solve this?
You have not provided the full interface however you will need to use an implementation of BagInterface to return a BagInterface. Replace
BagInterface<T> items = (T[]) new Object[total];
With
BagInterface<T> items = new ArrayBag();
or whatever the appropriate constructor for your ArrayBag class is (again, you have not provided enough code for me to know). Providing BagInterface has an add(T) method this should work, however you will also need to adjust how you are accessing the anotherBag. I am going to assume that you have an instance variable called bag which is an array of T. In this case, change the add in the second loop from:
items.add(anotherBag[i]);
to
items.add(anotherBag.bag[i]);
If this is not helpful please provide more information and context.
This question already has answers here:
How to return multiple objects from a Java method?
(25 answers)
Closed 9 years ago.
How to create a JAVA function with multiple outputs?
Something like:
private (ArrayList<Integer[]>, int indexes) sortObjects(ArrayList<Integer[]> arr) {
//...
}
Java's not like Python - no tuples. You have to create an Object and wrap all your outputs into it. Another solution might be a Collection of some sort, but I think the former means better encapsulation.
In some cases it is possible to use method arguments to handle result values. In your case, part of the result is a list (which may be updated destructively). So you could change your method-signature to the following form:
private int sortObjects(ArrayList<Integer[]> input, ArrayList<Integer[]> result) {
int res = 0;
for (Integer[] ints : input) {
if (condition(ints) {
result.add(calculatedValue);
res++
}
}
return res;
}
You cannot, you can either
Create a wrapper return object
Create multiple functions
Use an object as return value.
class SortedObjects { private ArrayList<Integer[]> _first; int _indexes; ...getter/setter/ctor... }
private SortedObjects sortObjects(ArrayList<Integer[]> arr) { ... }
You cannot.
The simple solution is to return an array of objects. A more robust solution is to create a class for holding the response, and use getters to get the individual values from the response object returned by your code.
You have to create a class which includes member variables for each piece of information you require, and return an object of that class.
Another approach is to use an Object which wraps the collection.
class SortableCollection {
final List<Integer[]> tables = ...
int indexes = -1;
public void sortObjects() {
// perform sort on tables.
indexes = ...
}
}
As it operates on a mutable object, there is no arguments or return values.