How to creart an ArrayList from array? - java

I am trying to create an ArrayList from a given array. This is the array I have:
public class Warehouse
{
private final static int MAX = 60;
private Item [] stock;
private int numItems;
public Warehouse()
{
stock = new Item[MAX];
numItems = loadData();
}
Now where should I change the processing from an array to an arraylist? Is this supposed to be done in the constructor or somewhere else? Thanks.

Why not use this?
List<Item> stockList = Arrays.asList(stock);

Just keep a separate class for the array and within the class that you want to get that specific array you can create an ArrayList Object.
public class ArrayaData {
public int Id;}
And the within the next class,
public class ClassYouWant {
ArrayList<ArrayaData> arrayList ;
}
and when ever you want to add a value to that array just create a new instance and then save it.
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value you want.."
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value 2 you want.."
Or you can simply set it in a Loop as well,
int arraySize = 5; //Size of the array you want
for (int i = 0; i < arraySize; i++) {
arrayList = new ArrayList<ArrayData>();
arrayList.Id = "Value you want";
}
And to get the vlaues you can use a Loop also,
int arraySize = arrayList.size(); //Size of the created arrayList
int value;
for (int i = 0; i < arraySize; i++) {
value = arrayList.get(i);
Toast.makeText(this, "Value " + i + ":" + value, Toast.LENGTH_SHORT).show();
}
Hope this helps..

Related

Java - How can I print out a value as a word after BubbleSorting?

I used integer so that I can write out Numbers as an input, but now i would like the programm to output the number as Words again.
public class KartenSort {
private int zwei = 2;
private int drei = 3;
private int vier = 4;
private int fuenf = 5;
public int[] liste ={drei,zwei,fuenf,vier};
public int[] sortieren(){
int unsortiert;
for(int sortiert = 0; sortiert < liste.length -1; sortiert++){
if(liste[sortiert] < liste[sortiert+1]){
continue;
}
unsortiert = liste[sortiert];
liste[sortiert] = liste[sortiert+1];
liste[sortiert+1] = unsortiert;
sortieren();
}
return liste;
}
public static void main (String[] args){
KartenSort bs = new KartenSort();
int[] array = bs.sortieren();
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(sortiert + 1 +":" + array[sortiert]);
}
}
}
thank you in advance
In your case you could use Map
Map<Integer,String> numbers = new HashMap<>();
numbers.put(2, "zwei");
numbers.put(3, "drei");
numbers.put(4, "vier");
numbers.put(5, "funf");
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(numbers.get(array[sorted]));
}
The array liste does not contain Strings (what you probably mean by "words").
I think, you wanted to have something like
String[] liste = ...
Your version of liste is
int[] liste = ...
This means it contains integer numbers, not strings. Although you write
int[] liste = {drei,zwei, ...}
the content of the array are still integer numbers. drei is a variable and you will get the value of the variable into the list. The value of drei is the integer value 1.
When you have the value 1 there is no reference back to the name of the variable that had hold it some time ago.

How to setText of JTextfield to a method with an array

I have a class called ShoutBox, and there it has this array and this method:
String messages[] = new String[10];
//declare 10 arrays
messages[0] = "Miley";
messages[1] = "Katy";
messages[2] = "Gaga";
messages[3] = "Beyonce";
messages[4] = "Taylor";
messages[5] = "Missy";
messages[6] = "Nicki";
messages[7] = "Adele";
messages[8] = "Rihanna";
messages[9] = "Selena";
String x = new ShoutBox().shoutOutCannedMessage(messages);
System.out.println(x);
public String shoutOutCannedMessage(String[] messages) {
for (int i = 0; i < messages.length; i++) {
System.out.println(i+". "+messages[i]);
}
System.out.print("Select a message: ");
int n = scan.nextInt();
String message = messages[n];
return message;
}
And then I have a another class for GUI, how to I make that result appear in a JTextField when an action is perform?
private void shoutOutMessageActionPerformed(java.awt.event.ActionEvent evt) {
JTextArea.setText(????);
}
Thanks!
Assuming that you want to show the next phrase in the array in response to an event and not show all phrases all at once:
Give your class an int index counter field, such as private int shoutIndex and initialize it to 0.
On any pertinent event (such as in an ActionListener), increment that index, e.g., shoutIndex++
Then make sure that the index is not larger than the length of the array using the remainder operator: shoutIndex %= messages.length
Then get the corresponding item from the array using the index, messages[shoutIndex], and use it to set the text of the JTextField.

Java: How to use functions of a class which has been instantiated by ArrayList

Here is just a simple example. Obviously there are simpler ways to set everything up within the constructor, but the arrayList I'm actually working with has already been set up, I just need to change individual sections of it. There HAS to be a way to call a class's functions in ArrayList, but for the life of me I can't figure out how.
import java.util.ArrayList;
public class ArrayTest{
public static void main(String[] args){
//Here's an example of a regular array:
Length[] lArray = new Length[3];
for (int i = 0; i < 3; i++){
lArray[i].setLength(i + 1);
}
//Here's how I was hoping ArrayList would function:
ArrayList<Length> lList = new ArrayList<Length>(3);
for (int i = 0; i < 3; i++){
lList[i].setLength(i + 1);
// --OR--
lList.setLength(i, i + 1);
}
}
}
Here's the length class:
public class Length{
private int length;
Length(){
length = 0;
}
Length(int s){
length = s;
}
public void setLength(int s){
length = s;
}
}
Thanks!
You add elements to the ArrayList with add.
Since it's an ArrayList<Length>, you add Length objects:
lList.add(new Length());
And in your specific loop :
ArrayList<Length> lList = new ArrayList<Length>(3);
for (int i = 0; i < 3; i++){
Length l = new Length();
l.setLength(i+1);
lList.add(l);
}
BTW, the array initialization is also missing an important initialization :
for (int i = 0; i < 3; i++){
lArray[i] = new Length(); // added
lArray[i].setLength(i + 1);
}
If the ArrayList already contains the elements, and you just want to modify them, you can write something like this:
lList.get(i).setLength(i + 1);
assuming that the ArrayList contains the ith element.
You could create a method with your operation/algorithm like
public void foo(){
System.out.println("some algorithm!");
}
inside Length class. This will operate on each instance of Length class.
And for iterating, you can use
ArrayList<Length> lList = new ArrayList<Length>(3);
for (Length l : lList){
l.foo();
}
This will call everything you code inside foo.

android listview adapter combine two arrays

I'm wornig sqllite.i have some tables and i select name for example Customer Table and Price from AnotherTable. and i received two array list .first name's array list and secods price's array list.
this is a my source
private ArrayList<GetDictioanyClassByPosition> GetPKFromTable() {
price_array.clear();
ArrayList<GetDictioanyClassByPosition> my_list = d_Helper
.getAllPriceByPosition(0);
for (int i = 0; i < my_list.size(); i++) {
String AllPrice = my_list.get(i).getDictionaryPrice();
GetDictioanyClassByPosition cnt = new GetDictioanyClassByPosition();
System.err.println(AllPrice + "AllPrice");
cnt.setDictionaryPrice(AllPrice);
price_array.add(cnt);
}
return price_array;
}
this is a method to check price's array list and this method check name's array list
public void AllInfoFromLoanAnalysis() {
name_list.clear();
ArrayList<GetAllDictionariesClass> contact_array_from_db = d_Helper
.getAllInformationFromLoanAnalysis_Table(1, 1);
Log.e("Sizee", contact_array_from_db.size() + "sizee");
for (int i = 0; i < contact_array_from_db.size(); i++) {
int DictionaryID = contact_array_from_db.get(i).getDictionaryID();
System.out.println(DictionaryID + "DictionaryID");
GetDictioanyClassByPosition object = new GetDictioanyClassByPosition();
String name = null ;
ArrayList<GetDictioanyClassByPosition> DictionaryIdList = d_Helper
.GetDictionaryIdList(DictionaryID);
System.out.println(DictionaryIdList.size() + "DictionaryIdList");
Log.e("Sizee2", DictionaryIdList.size() + "sizee2");
for (int j = 0; j < DictionaryIdList.size(); j++) {
name= DictionaryIdList.get(j).getDictionaryName();
Log.e("object", name + "object");
object.setDictionaryName(name);
name_list.add(object);
}
for (int j = 0; j < price_array.size(); j++) {
String AllPrice = price_array.get(i).getDictionaryPrice();
object.setDictionaryPrice(AllPrice);
object.setDictionaryName(name);
price_array.add(object);
}
agroproductslistview.setAdapter(agroproduct_adapter);
}
}
and i called my BaseAdapter Like this
_adapter = new LoanProductAdapter(
getApplicationContext(), R.layout.productlistadapter,
name_list);
public class GetDictioanyClassByPosition {
private String DictionaryName;
private String DictionaryPrice;
public String getDictionaryName() {
return DictionaryName;
}
public void setDictionaryName(String DictionaryName) {
this.DictionaryName = DictionaryName;
}
public String getDictionaryPrice() {
return DictionaryPrice;
}
public void setDictionaryPrice(String DictionaryPrice) {
this.DictionaryPrice = DictionaryPrice;
}
}
i can selected and show my prices and names in different array list but i want to marge both array list and would adapter in my list view
.how i can solve my problem?
if anyone knows solution please help me
thanks
Please refer below example.
public ArrayList<customObject> _historyArrayList = new ArrayList<customObject>();
public ArrayList<customObject> _completedArraylist = new ArrayList<customObject>();
For merging simply use:
_historyArrayList.addAll(_completedArraylist);
Note: Make sure your customObject are same

doubling Array size if full

I have an array of objects. When the array fills up, I want to make a new array twice as large as the old one, and transfer all the elements over. I'm doing something wrong, I think its something to do with I'm not creating the correct reference to the new array. Here's my code, any help figuring this out would be appreciated.
private int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
private int numberOfElements = 0;
public int getNumOfElements(){
return numberOfElements;
}
public void setDirectorySize(int size){
DIRECTORY_SIZE = size;
}
public int getDirectorySize(){
return DIRECTORY_SIZE;
}
public void addEntry(String surname, String initial, String num) {
// TODO add an entry to an array, also increments numberOfElements variable tracking whats in array
if(getNumOfElements() == getDirectorySize()){ // if array is full
doubleArraySize(); // put temp values into new bigger directory array
}
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
numberOfElements++;
}
private void doubleArraySize(){
Entry[] temp = new Entry[DIRECTORY_SIZE]; //make new temp array same size as old one
for(int i = 0; i < DIRECTORY_SIZE ; i++){
temp[i] = directory[i]; // cycle through array putting all values into temp
// works up to here
}
setDirectorySize(DIRECTORY_SIZE*2); // double size of array
Entry[] directory = new Entry[DIRECTORY_SIZE]; // create new, double size directory array
for(int i = 0; i < temp.length ; i++){
directory[i] = temp[i];
}
}
private int findFreeLocation() {
int i;
for (i = 0; i < DIRECTORY_SIZE; i++)
{
if(directory[i] == null)
{
break;
}
}
return i;
}
In doubleArraySize() function , this is the issue :
Entry[] directory = new Entry[DIRECTORY_SIZE];
// you are not assigning it to the class attribute directory
// instead you are creating a local array directory
Make the following change :
this.directory = new Entry[DIRECTORY_SIZE];
// this will assign the newly created array to the class attribute
Note : I personally prefer to use this pointer to refer to class attributes so that it makes my code more readable, and its clear to everyone that the variable in question is a class attribute rather than local variable.
**SIZE has already double by this point. No need to multiple by 2
I remember doing something exactly like this when I was making a Vector ADT. However, I used instance variables instead of methods in my code for element number and the capacity. I definitely didn't initialize a Vector inside a method for a Vector.
setDirectorySize(DIRECTORY_SIZE*2); // double size of array
Entry[] directory = new Entry[DIRECTORY_SIZE]; // create new, double size directory array
Isn't DIRECTORY_SIZE an instance variable? Because if it is, I don't think you can initialize an object using an instance variable from the object you are overwriting.
Putting my code into your context, it would look something like this:
private void doubleDirectorySize()
{
Entry[] new_array = new Entry[new_directory_size*2];
for (int i = 0; i < directory_size; i++)
{
new_array[i]= directory[i];
}
directory= new_array;
}
This only works if directory was initialized to null, though, moving the pointer directory to the new array.

Categories