Let's say I have an array of objects like dummies[] below. I want to find the index of array objects where their attribute a == 5 or a > 3 etc.
class Dummy{
int a;
int b;
public Dummy(int a,int b){
this.a=a;
this.b=b;
}
}
public class CollectionTest {
public static void main(String[] args) {
//Create a list of objects
Dummy[] dummies=new Dummy[10];
for(int i=0;i<10;i++){
dummies[i]=new Dummy(i,i*i);
}
//Get the index of array where a==5
//??????????????????????????????? -- WHAT'S BEST to go in here?
}
}
Is there any way other than iterating over the array objects and check for the conditions? Does using ArrayList or other type of Collection help here?
// Example looking for a==5
// index will be -1 if not found
int index = -1;
for( int i=0; i<dummies.length; i++ ) {
if( dummies[i].a == 5 ) {
index = i;
break;
}
}
Related
I have an assignment to create an array class where there are 2 constructors where each constructor sets a different size for the array.
The array is already an instance variable along with another instance variable to keep track of the current position in the array.
I have to create a method called add with an integer parameter that will store the parameter value in the array at the index of the position variable, then add 1 to the position variable. If the incremented position variable is outside the bounds of the array, the method calls the addspace method.
The addspace method creates a new array 25% larger than the instance variable array, copies all the values of the instance array to the new array, and assigns the new array to the instance variable.
I also need a method called size that will return the value in the position variable and a method called get that with 1 parameter(an index), the method returns the value at the parameter index.
The last thing I need is a print method that uses a for loop to print the values in the array.
So far this is what I have
public class ArrayClass
{
private int array[];
private int x=0;
public ArrayClass()
{
this.array= new int[10];
add(1);
getThat(0);
print();
}
public ArrayClass(int y)
{
this.array= new int[y];
add(2);
getThat(0);
print();
}
public void add(int a)
{
array[x]=a;
x++;
if(x>array.length)
addspace();
}
public void addspace()
{
double d=array.length+(array.length*0.25);
int v=(int)d;
int newArray[]= new int[v];
for(int i=0; i<array.length; i++)
{
newArray[i]=array[i];
System.out.println(newArray[i]);
}
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
for(int i=0; i<array.length; i++)
System.out.println(array[i]+" ");
}
public static void main(String[] args)
{
new ArrayClass();
new ArrayClass(5);
}
}
I know the title only asks for help with the first method but if someone would be kind enough to help with the other methods and the reason why my code won't run and print what I want it to that would be much appreciated.
Use the ArrayClass for only for declaring your functionality.Call add method as obj.add(number) until and unless you need to add something inside ArrayClass constructor itself.
Modified these things as per my understanding
In your add method you are assigning the value first and then adding space if the array is full, in this case, you are increasing the size even if it might not be needed (i.e not calling add method again).
Instead of this increase the size only when you require it.
In print function you are iterating through the whole array.Modified to-> it will iterate till the last index of value (i.e x)
package com.example;
public class ArrayClass
{
private int array[];
private int x=0;
private final int DEFAULT_SIZE=4;
public ArrayClass(){
this.array = new int[DEFAULT_SIZE];
}
public ArrayClass(int size){
this.array = new int[size];
}
public void add(int number){
//check whether array have space or not .if not then increase the space.
if(x > this.array.length-1){
addSpace();
}
array[x] =number;
x++;
}
private void addSpace(){
double newSize = array.length + array.length * 0.25;
int tempArray[] = new int[(int) newSize];
for(int i=0; i<array.length; i++){
tempArray[i]=array[i];
}
this.array = tempArray;
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
//instead of of printing the whole array Printed till last value index.
for(int i=0; i<x; i++)
System.out.println(array[i]+" ");
}
}
From the main method
ArrayClass ac1 = new ArrayClass();
ac1.add(5);
ac1.add(4);
ac1.add(5);
ac1.add(4);
ac1.add(7);
ac1.add(19);
ac1.print();
ArrayClass ac2 = new ArrayClass(5);
ac2.add(1);
//rest of your function call here
I am facing a problem where I need to sort a String array in alphabetical order. I am able to sort one array, but the problem starts when there are 2 more arrays, that correspond to the first array. Each value in each array should be in the same place, to make information not messed up. After sorting array1, it is in alphabetical order, but i don't have any idea how to make values from array2 and array3 change the positions the same like in array1 after sorting is finished.
My code so far is:
public void sort()
{
boolean finish = false;
while(finish == false){
finish = true;
for(int i=0;i<Country.length-1;i++)
{
int num = 0;
if(Country[i] != null && Country[i + 1] != null)
{
String name1=Country[i]; String name2=Country[i+1];
num=name1.compareTo(name2);
}
else if(Country[i] == null && Country[i + 1] == null){
num = 0;
}
else if(Country[i] == null){
num = 1;
}
else {
num = -1;
}
if(num>0)
{
String temp=Country[i];
Country[i]=Country[i+1];
Country[i+1]=temp;
finish=false;
}
}
}
By far the most recommended way is to re-design your program, and arrange all the related items in a single class. This is what objects are for, after all. Then you can make the object Comparable, give it a compareTo method, and sort it.
But if you are really unable to do that, what you should do is, whenever you exchange any two items in your sort array, make sure you exchange the corresponding items in the other arrays.
So, if you have arrays country, capital and headOfState, you will have to write something like:
String temp=country[i];
country[i]=country[i+1];
country[i+1]=temp;
temp=capital[i];
capital[i]=capital[i+1];
capital[i+1]=temp;
temp=headOfState[i];
headOfState[i]=headOfState[i+1];
headOfState[i+1]=temp;
This way, whenever you move anything in your main array, you'll also be moving the respective item in the other arrays, so they will stay together.
But again, it's much more preferred if you re-designed your program.
Also note the Java language conventions - variable names should not start with a capital letter, only type names should.
If you want all the array to be swaped based on the compare you did in the country array. You can just swap more than one array after one compare.
If(array1[i] > array1[i+1]){
Swap(array1[i],array1[i+1)
Swap(array2[i],array2[i+1])
}
By using a swap function, you can make it more simpler to do swaping in much more array.
You have to swap elements in Country and City arrays simultaneously.
public class BubbleSortTmp {
public String[] Country = {"z", "h", "a"};
public int[] City = {3, 2, 1};
public void printCountry() {
for (String s : Country) {
System.out.printf("%s ", s);
}
System.out.println();
}
public void printCity() {
for (int s : City) {
System.out.printf("%s ", s);
}
System.out.println();
}
public void sort() {
for (int outer = Country.length - 1; outer > 0; outer--) {
for (int inner = 0; inner < outer; inner++) {
if (Country[inner].compareTo(Country[inner+1]) > 0) {
swapCountry(inner, inner+1);
swapCity(inner, inner+1);
}
}
}
}
private void swapCountry(int first, int second) {
String tmp = Country[first];
Country[first] = Country[second];
Country[second] = tmp;
}
private void swapCity(int first, int second) {
int tmp = City[first];
City[first] = City[second];
City[second] = tmp;
}
public static void main(String[] args) {
BubbleSortTmp bs = new BubbleSortTmp();
System.out.println("Before: ");
bs.printCountry();
bs.printCity();
bs.sort();
System.out.println("After: ");
bs.printCountry();
bs.printCity();
}
}
My method is trying to find a certain card with a suit and a value previously described in enums.
My original code is:
public int find(Suit s, Value v) {
for(int i=0; i<numCards; i++) {
if(cards[i].getSuit() == s && cards[i].getValue() == v) {
return i;
}
}
return -1;
}
cards was an array and I've already converted it to an array, but how do I modify the code to apply to an ArrayList? Is there a method I should be using or would HashTables help me?
Maybe this (assuming it's cards that is the arraylist):
public int find(Suit s, Value v) {
for(int i=0; i<cards.size(); i++) {
if(cards.get(i).getSuit()==s && cards.get(i).getValue()==v) {
return i;
}
}
return -1;
}
This should traverse through every element in the ArrayList for cards
You should really never use arrays. They are inherently less flexible and reliable.
You should have a Card class like this:
public class Card implements Comparable<Card> {
public int compareTo(Card other) { return this.value - other.value;}
}
Then have
List<Card> cards;
Notice I am specifying ArrayList or LinkedList .. just List.
Then you can just use
int index = Collections.binarySearch(cards,new Card(...));
Implementing a for loop is just not the way to go.
format: get(index):Object.
public class MyArrayList {
public String[] arrays = {};
public MyArrayList() {
arrays = new String[10];
}
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
}
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
With this code it prints out:
Testing constructor, add(object) and size()
The zoo now holds 10 animals: 0 1 2 3 4 5 6 7 8 9
Obviously my code for get method is very wrong but instead of printing out the numbers it should print out "Ant","Bison,"Camel" etc.
All help appreciated for code as I'm a very new programmer. Thanks.
Fixing your Get Method
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
Okay, so let's look at this shall we? There's a few values that the user can provide..
i < 0
0 < i < size of array <-- The only valid one.
i > size of array
So first you need to check for that!
if(i > 0 && i < arrays.length) {
// This is a valid index!
}
Okay, so you know it's a valid index. Step two is retrieving the value..
return arrays[i];
And finally, the return type needs to be set. At the moment it is int. It needs to be String in this example..
public String get(int i)
It's that simple! When you call printZoo(), you'll see the values and not their indices.
Onto your Objects
You can have an array of type Object without importing any classes. This will change arrays of type String[] to..
Object[] arrays;
Your Code is technically correct, but if you want to return string values in run time, you must change the value returned in method get to String as in
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
to
public String get(int i){
return arrays[i];
}
Also in your method printZoo(), you have another loop, so i'd imagine your code printing out duplicate values. so why don't you have the printZoo Method dealing with the for loop and the get() method above displaying the values
So Change your get method to the one i have here, and everything should work for you
If it doesn't Work, then try these pieces of Code
MyArrayList.java
public class MyArrayList{
public String[] arrays = {};
public int i = 0;
public MyArrayList() {
arrays = new String[10];
}
public void add(String a)throws ListFullException{ //Add to List if Arraylist is not full
if(i != arrays.length-1){
arrays[i] = a;
i++;
}
else{
throw new ListFullException("List Full");
}
}
public String get(int i){
return arrays[i];
}
public int getArraySize(){
return arrays.length;
}
}
MyArrayListTest.java
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.getArraySize() + " animals: ");
for (int j = 0; j < zoo.getArraySize(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
And the Exceptions class
ListFullException.java
public class ListFullException extends RuntimeException{
public ListFullException(String m){
super(m);
}
}
I hope this will be a great study tool for you, if you feel this has helped you, upvote and accept :) :P
It is printing an int because you are calling zoo.get(j) and get() returns ints:
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
You need to return a String, something along the lines of:
public String get(int i){
return arrays[i];
}
I have a very simple program and I just need to check an array for a value in it.
I have a class called bulkBean. this is it.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean type in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I create 2 instances of bulk bean and I set values to them. Then I added those two instances to an array. Then I pass that array to the method to check for a value(also given as a parameter. In this case it is 1.). If the array contains that value, it should return true, otherwise false.
whatever value I enter, it return false.
Why do I get this issue?
Arrays.asList() returns a List which has a single element - an array. So, you are actually comparing against an array. You need to compare against each value in the array.
As TheListMind told, Arrays.asList() taken on an int[] gives you a list containing the array.
Personally, I would construct directly the List instead of constructing the array, or even better (no need of array instanciation), test while iterating the bulk array :
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
The mistake you made here is , you created the int array which must be Integer array because Arrays.asList().contains(Object o); makes the input parameter also Integer(Integer i). int is not an object Integer is the object. Hope it will work.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Change the method as below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}