Overrided add isn't working - java

Add is supposed to be an overrided method in which the string is put in the arraylist in alphabetical order, but whenever I execute the program, the Arraylist is always in the order that I added it in.
Here's Test:
import java.util.*;
public class Test
{
private static ArrayList x=new ArrayList();
private static ArrayList<String> li=new ArrayList<String>();
private static SortedList s=new SortedList();
// private static Person p[]=new Person[4];
// private static Fraction f[]=new Fraction[5];
public static void main(String args[])
{
//number 1
x.add(5);
x.add(6);
x.add(1.5);
x.add(7);
x.add(2.5);
System.out.println(average(x,2)); //5.5
System.out.println(average(x,7)); //4.4
//number 2
li.add("Hi");
li.add("del");
li.add("there");
li.add("del");
li.add("you");
li.add("del");
System.out.println(li);
takeOut(li,"del");
System.out.println(li);
//number 3
s.add("dog");
s.add("anteater");
s.add("kewl");
s.add("kitty");
s.add("a");
System.out.println(s);
//number 4
// p[0]=new Person("Kremer","Jim");
//p[1]=new Person("Shi","Kevin");
// p[2]=new Person("Shi","Rebecca"); //I know I spelled your name wrong, Rebecca. (I needed two last names to be the same)
// p[3]=new Person("Herman", "Jimmy");
// Arrays.sort(p); //static method in java.util.Arrays
// for(int i=0; i<p.length; i++)
System.out.println(p[i].getFirstName()+" "+p[i].getLastName());
//number 5
f[0]=new Fraction(4,5);
f[1]=new Fraction(5,4);
f[2]=new Fraction(-8,3);
f[3]=new Fraction(6,5);
f[4]=new Fraction(-1,2);
Arrays.sort(f);
for(int i=0; i<f.length; i++)
System.out.println(f[i].getNum()+"/"+f[i].getDenom());
}
//number 1
public static Double average(ArrayList samples, int num)
{
double sum=0.0;
if(num>samples.size())
{
for(int i=0; i<samples.size(); i++)
{
if(samples.get(i) instanceof Integer)
sum+=(Integer)samples.get(i);
else
sum+=(Double)samples.get(i);
}
return sum/samples.size();
}
else
{
for(int i=0; i<num; i++)
{
if(samples.get(i) instanceof Integer)
sum+=(Integer)samples.get(i);
else
sum+=(Double)samples.get(i);
}
return sum/num;
}
}
//number 2
public static void takeOut(List<String> words, String del)
{
for(int i=0; i<words.size(); i++)
{
if(words.get(i).equals(del))
{
words.remove(i);
i--;
}
}
}
}
And here's SortedList:
import java.util.ArrayList;
import java.util.List;
import java.lang.String;
public class SortedList extends ArrayList<String>
{
private ArrayList<String> a;
public SortedList()
{
a = new ArrayList<String>(10);
}
public SortedList(int cap)
{
super(cap);
}
public boolean add(String x)
{
if(a.size()!=0)
{
for(int i=0; i<a.size(); i++)
{
if(i==a.size()-1)
if(x.compareTo(a.get(i))>=0)
super.add(x);
else
{
if(i==0)
if(x.compareTo(a.get(i))<=0)
super.add(0,x);
if(x.compareTo(a.get(i))>=0 && x.compareTo(a.get(i+1))<=0)
super.add(i+1,x);
}
}
}
else
super.add(x);
return true;
}
}
Thanks in advance!

a.size() != 0 is always false as your SortedList implementation doesn't add any elements in the list a. This results that super.add(x) is always used and the overridden add-method doesn't actually modify the behavior of an ArrayList

User,
Look up Java Collections interface. Java can sort these elements alphabetically for you:
ArrayList<String> a = new ArrayList<String>
a.add("world");
a.add("hello");
Collections.sort(a);
//sorted alphabetically now
If the default sort is the wrong direction, just implement your own Comparator and call:
Collections.sort(a, myComparator);
This should do what you are seeking, unless of course this is a homework assignment...

Related

Hackerrank Mark and Toys Question my solution not working for large input testcases

Below is the problem statement from hackerrank
Mark and Jane are very happy after having their first child. Their son loves toys, so Mark wants to buy some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of toys Mark can buy? For example, if prices = [1,2,3,4] and Mark has k=7 to spend, he can buy items [1,2,3] for 6, or [3,4] for 7 units of currency. He would choose the first group of 3 items.
Below is code I wrote for this problem which involves backtracking technique
import java.util.ArrayList;
import java.util.Collections;
public class MarkAndToys {
static ArrayList<Integer> possibleSolutions = new ArrayList<>();
static boolean findSolution(int[] prices,int amount,int left,int length,int items){
// Base case: if whole array was iterated and amount is >=0 then we got a solution
if(left >= length){
if(amount>=0){
possibleSolutions.add(items);
return true;
}
return false;
}
// Key idea: prices[left] is chosen or it is not.
// Deal with prices[left], letting recursion
// deal with all the rest of the array.
// Recursive call trying the case that prices[left] is chosen --
// subtract it from amount in the call.
if (findSolution(prices,amount-prices[left],left+1,length,items+1)) return true;
// Recursive call trying the case that prices[left] is not chosen.
if (findSolution(prices,amount,left+1,length,items)) return true;
// If neither of the above worked, it's not possible.
return false;
}
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
if(findSolution(prices,k,0,prices.length,0)){
//if solutions are found then return maximum of them
return Collections.max(possibleSolutions);
}
return 0;
}
public static void main(String[] args) {
System.out.println(maximumToys(new int[]{1,12,5,111,200,1000,10}, 50));
}
}
This seems to be working fine:
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
Arrays.sort(prices);
int sum = 0;
int index = 0;
for(int i = 0; i < prices.length; i++) {
sum+=prices[i];
index = i;
if(sum > k) {
break;
}
}
return index;
}
package Scanarios;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Toys {
public static void main(String[] args) {
Toys t=new Toys();
int[] a = {3,6,2,1,4,5};
int q=1;
int n=6;
ArrayList<Integer> queries[]=new ArrayList[n];
ArrayList<Integer> result=new ArrayList();
for (int i = 0; i < n; i++) {
queries[i] = new ArrayList<Integer>();
}
queries[0].add(10);
queries[0].add(2);
queries[0].add(2);
queries[0].add(5);
result=t.maximumToys(n,a,q,queries);
System.out.println(result);
}
public ArrayList<Integer> maximumToys(int n, int a[], int q, ArrayList<Integer> queries[]) {
ArrayList<Integer> arrlist=new ArrayList();
for(int z=0;z<q;z++) {
int[] arr=queries[z].stream().mapToInt(i -> i).toArray();
int cost=arr[0];
int k=arr[1];
int count=0;
int[] proxyarr=new int[n-1];
proxyarr =removeBrokenPrice(a,arr,k);
Arrays.sort(proxyarr);
for(int i=0;i< proxyarr.length;i++) {
cost -=proxyarr[i];
if(cost > 0) {
count++; }else {
break;
}
}
arrlist.add(count);
}
return arrlist;
}
int[] removeBrokenPrice (int a[],int b[],int k){
int count=0;
for(int i=k;i <= b.length-1;i++) {
for(int j=0;j<a.length;j++) {
if(j==b[i]-1) {
a[j]=-1;
count++;
}
}
}
int[] proxyarr=new int[a.length-count];
for(int i=0,j=0;i< a.length;i++)
{
if(a[i]==-1) {
continue;
}else {
proxyarr[j++]=a[i];
}
}
return proxyarr;
}
}

Adding multiple "randomly generated" objects to ArrayList results in adding the same object multiple times

I have a class Ttp which has a ArrayList<City>loaded from file. In constructor of Ttp I randomly shuffle a list read from file and assign it to the object.
public class Ttp {
private ArrayList<City> cities;
public Ttp() {
cities = Utils.shuffleArray(Loader.getCities());
}
}
This way I get 10 objects with nicely shuffled arrays:
public static void main(String args[]) {
Loader.readFile("easy_0.ttp");
for(int i=0; i<10; i++){
System.out.println(new Ttp());
}
}
But in this scenario, when I try to create ArrayList<Ttp> I get a collection full of the same objects (instances of Ttp with the same arrays of cities)
public static void main(String args[]) {
Loader.readFile("easy_0.ttp");
ArrayList<Ttp> arrayList = new ArrayList<>();
for(int i=0; i<10; i++){
arrayList.add(new Ttp());
}
arrayList.forEach(System.out::println);
}
Shuffle function:
public static <T> ArrayList<T> shuffleArray(ArrayList<T> arrayList) {
if (arrayList != null && arrayList.size() > 0) {
int numberOfRolls = Random.getGenerator().nextInt((arrayList.size() - arrayList.size() / 3) + 1) + arrayList.size() / 3;
int indexA;
int indexB;
T objectA;
for (int i = 0; i < numberOfRolls; i++) {
indexA = Random.getGenerator().nextInt(arrayList.size());
indexB = Random.getGenerator().nextInt(arrayList.size());
objectA = arrayList.get(indexA);
arrayList.set(indexA, arrayList.get(indexB));
arrayList.set(indexB, objectA);
}
}
return arrayList;
}
To pick random indexes in shuffle function I am using java.util.Random:
public class Random {
private static final java.util.Random generator = new java.util.Random();
public static java.util.Random getGenerator() {
return generator;
}
}
If Loader.getCities() returns the same list every time that means shuffleArray() is shuffling the same list over and over and every Ttp.cities has a reference to the same unitary list.
The fix is to make a copy somewhere. It could be in getCities(), it could be in shuffleArray(), or it could be in the Ttp constructor:
cities = Utils.shuffleArray(new ArrayList<>(Loader.getCities()));

android Arrange data in descending order

I have following data in string(comma format) (Name,Mark)
A,20,B,10,C,30
I want to convert into Descending order like :
C,30,A,29,B,10
Please help me how can i implement in android ?
Here is code what i have prepared....
public class custom_sort {
public String name;
public int mark;
public custom_sort(String a, int b) {
// TODO Auto-generated constructor stub
name = a;
mark = b;
}
void setname(String s)
{
name=s;
}
void setmark(int s)
{
mark = s;
}
String getname()
{
return(name);
}
int getmark()
{
return(mark);
}
}
Thanks in Advance,
There are many ways of doing this. I see that you have already made a class: custom_sort. We can use this to sort it, if we just make it comparable. We do this by implementing the Comparable interface.
public class custom_sort implements Comparable{
Then all you need to do is implement the one required method:
#Override
public int compareTo(custom_sort cs) {
/*
This method should return 0 if the two objects are equal,
1 if this is biggest
and -1 if cs is biggest */
}
Then you can put all the custom_sorts in an List and just do Arrays.sort(yourArray).
You could also check out this post Android sort array
Use ArrayList rather than array of string.
This might not be the best solution but it works.
Initialize the ArrayList
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
Fill data inside the ArrayList
names.add("A");
scores.add(20);
....
Now sort them
private void sortScoreAndName() {
for (int i = 0; i < scores.size(); i++) {
for (int j = 0; j < i; j++) {
if (scores.get(i) > scores.get(j))
swap(i, j);
}
}
}
private void swap(int i, int j) {
int tempSco = scores.get(i);
String tempName = names.get(i);
scores.remove(i);
names.remove(i);
scores.add(i, scores.get(j));
names.add(i, names.get(j));
scores.remove(j);
names.remove(j);
scores.add(j, tempSco);
names.add(j, tempName);
}
Now your ArrayList is in descending order. You can get the corresponding data using.
names.get(poition);
scores.get(position);
try this:
import android.support.v4.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
String[] values = {"A", "20", "B", "10", "C", "30"};
List<Pair> pairs = new ArrayList<>();
for (int i = 0; i < values.length; i += 2) {
pairs.add(new Pair<>(values[i], Integer.parseInt(values[i + 1])));
}
Collections.sort(pairs, new Comparator<Pair>() {
#Override
public int compare(Pair lhs, Pair rhs) {
return ((Integer) rhs.second).compareTo((Integer) lhs.second);
}
});
The List pairs is now sorted like you wish. Check out the Pair class i used http://developer.android.com/reference/android/util/Pair.html
And if you want to convert it back following code will help you:
String[] newValues = new String[values.length];
int i = 0;
for (Pair pair : pairs) {
newValues[i] = (String) pair.first;
newValues[i + 1] = Integer.toString((Integer) pair.second);
i += 2;
}

Return element at position index. (No ArrayList)

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];
}

How to sort Integer Vector using Comparator and iterator?

I want to create Integer vector type Vector and to insert random 10 numbers.
Then I want to sort the Vector by using compareTo and to send two arguments type numbers to compare it.
but I miss something.
Many thanks for any help.
import java.util.*;
public class SortNumeric implements Comparable<SortNumeric>
{
private int ind =0;
public static void main(String args[])
{
Vector<Integer> vec = new Vector<>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++)
{
int rand = (int)(1000*Math.random());
vec.add(rand);
System.out.println(rand);
}
Arrays.sort(vec);
System.out.println("After sorting");
for(Integer intnum : vec)
{
System.out.println(intnum);
}
}
public int getNextCompar(){
if (vec.hasNext() && this.ind < 5){
this.ind++;
return vec.next();
}else{return 0;}
}
public int compareTo(SortNumeric other)
{
return (int) (vec.next() - this.getNextCompar());
}
}
class sortVectors implements Comparator<Integer>{
#Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if(o1<02){
return -1;
}else if(o1>o2)
return 1;
return 0;
}
}
public class sortVector{
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector<Integer> vect = new Vector<Integer>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++) {
int rand = (int) (1000 * Math.random());
vect.add(rand);
System.out.println(rand);
}
Collections.sort(vect,new sortVectors());
System.out.println("After Sorting");
for (Integer num : vect) {
System.out.println(num);
}
}
}
You don't need to implement Comparable for Integer, hence no compareTo is required. Also use Collections.sort instead of Arrays.sort. Here is your modified code example:
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String args[]) {
Vector<Integer> vec = new Vector<>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++) {
int rand = (int) (1000 * Math.random());
vec.add(rand);
System.out.println(rand);
}
Collections.sort(vec);
System.out.println("After sorting");
for (Integer intnum : vec) {
System.out.println(intnum);
}
}
}
Check this SO question for more details:
What function can be used to sort a Vector?
If you want to sort an array in a specific order, you need to create a Comparator.
Comparable is used when you want to sort the objects of a particular class when used in a collection or array.
In your case, you need to use a Comparator.
class MyComparator extends Compartor
{
public int compare(Integer a, Integer b)
{
return a - b;
}
}
In your Main class, call Arrays.sort(vec, new MyComparator());

Categories