Copy Lists method doesn't work - java

I'm trying to make a copy lists method as this one Collections.copy(,);
I want to make it my self so I made this one
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NewMain {
public static void main(String[] args) {
String[] a1={"asdasd","sadasd","asdasd"};
List<String> l1= Arrays.asList(a1);
String[] a2=new String[3];
List<String> l2= Arrays.asList(a2);
copy(l1,l2);
}
public static void copy(List<String> copy_from,List<String> copy_to){
for(int i=0;i<=copy_from.size();i++){
System.out.print( copy_from.containsAll(copy_to));
}
}
}
I know the problem from containsAll method , but what should I use ?

for(int i=0;i<=copy_from.size();i++){
System.out.print( copy_from.containsAll(copy_to));
}
Does nothing besides a sysout statement.
You want something along the lines of:
public static void copy(List<String> copy_from,List<String> copy_to){
if (copy_from.size() > copy_to.size())
throw new IndexOutOfBoundsException("Source does not fit in dest");
} else {
for(String toCopy : copy_from) {
copy_to.add(toCopy);
}
}
}
This is a for each loop that loops over every element in your copy_from list and adds it to your copy_to list.

This will behave the same way as Collections.copy.
public static void copy(List<String> copy_from,List<String> copy_to){
if (copy_to.size() < copy_from.size()) {
throw new IndexOutOfBoundsException("copy_to is too small.");
}
ListIterator<String> fromIter = copy_from.listIterator();
ListIterator<String> toIter = copy_to.listIterator();
while (fromIter.hasNext()) {
String next = fromIter.next();
toIter.next();
toIter.set(next);
}
}

I assume that you don't want to copy elements that are already there.
Then you can do it this way:
public static void copy(List<String> copy_from,List<String> copy_to){
if(copy_to==null){throw Exception("copy_to can't be null!")}
//additional checks should be added
for(String elem : copy_from){
if(!copy_to.contains(elem)){
copy_to.add(elem);
}
}
}

This should do assuming copy_from and copy_to can grow as we add elements.
public static void copy(List<String> copy_from,List<String> copy_to) throws Exception {
//handle exception according to your wish
if (copy_from !=null && copy_to == null) {
throw new Exception("Source is not empty by Destination is null");
}
for(String string : copy_from){
copy_to.add(string);
}
}

Related

Using LinkedList iterator not working in this case

Here I have the code that contains only one method that has 2 parameters. First one is of type linkedlist and second one is of type String. The idea here is that I call this function from the main method several time and each new item that gets added should be sorted from A-Z. But for some reason if I don't add return in the function (
else if(compareResult>0) {
iterator.previous();
iterator.add(element);
return;
}
)
then I get empty list printed out. Why is that?
public class Main {
public static void main(String[] args) {
LinkedList<String> list=new LinkedList<>();
addAndSortElements(list,"a");
addAndSortElements(list,"b");
addAndSortElements(list,"c");
addAndSortElements(list,"f");
addAndSortElements(list,"d");
System.out.println(list);
}
private static void addAndSortElements(LinkedList<String> linkedList, String element) {
var iterator= linkedList.listIterator();
while (iterator.hasNext()) {
String editedElement=element.toLowerCase();
int compareResult=iterator.next().toLowerCase().compareTo(editedElement);
if(compareResult==0) {
System.out.println("Element is already on the list");
***return;***
}
else if(compareResult>0) {
iterator.previous();
iterator.add(element);
return;
}
else {
}
}
iterator.add(element);
}
}
```
`
I have tried everything I said above.

Remove every nth employee doesn't work

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class vijftienpunt1 {
public static void downsize(LinkedList<String> employeeNames, int n) {
for (int i = 0; i < employeeNames.size(); i++) {
if(i%n==0) {
employeeNames.remove(i);
}
}
}
public static void main(String[] args) {
LinkedList<String> employeeNamess = new LinkedList<String>();
employeeNamess.add("Ab");
employeeNamess.add("Yo");
employeeNamess.add("Ik");
employeeNamess.add("Jij");
System.out.println(employeeNamess);
downsize(employeeNamess, 2);
System.out.println(employeeNamess);
}
}
When I run this doesn't work, it removes other nth elements, how can I fix this. I have tried more operations but it still doesn't work
Use Iterator whenever you want to remove elements from list.
try below code:
public static void downsize(LinkedList<String> employeeNames, int n) {
int i=1;
Iterator<String> iter=employeeNames.iterator();
while(iter.hasNext()){
iter.next();
if(i%n==0) {
iter.remove();
}
i++;
}
}

find duplicate element in array list

import java.util.ArrayList;
public class list {
protected ArrayList<String> a = new ArrayList<String>();
public boolean ad(String aa)
{
boolean t=true;
a.add(aa);
for(String value : courses)
{
if(a.contains(value))
{
a=false;
}
else
{
a=true;
}
}
return a;
}
}
this program should return false if arraylist course contains duplicate elements.else if we are inserting new element return true.
expected output for above code is
true
but it only returns false for any condition.
You can simply utilize ArrayList#contains to verify if an element already exists within the List.
public boolean addCourse(String course) {
if (courses.contains(course)) {
return false;
}
return courses.add(course);
}
You are adding course in the list and then iterating thr the list, so it always gives you true. ArrayList allows duplicates.
if(courses.contains(value))
will always return true as you are adding the course before this in arraylist.
Suggestion: You should use Set than list if you want to avoid duplicates.
Instead of using ArrayList, how about using HashSet to keep your courses ?
http://beginnersbook.com/2013/12/hashset-class-in-java-with-example/
Try the code below:
import java.util.ArrayList;
public class list {
protected ArrayList<String> courses = new ArrayList<String>();
protected String temp = "";
public list(String str, String str2) {
}
public boolean addCourse(String course) {
boolean a = true;
if (courses.isEmpty()) {
courses.add(course);
temp = course;
} else {
if (temp.equalsIgnoreCase(course)) {
a = false;
temp = "";
} else {
a = true;
courses.add(course);
temp = course;
}
}
return a;
}
public static void main(String[] args) {
list inst = new list("John", "WIU");
System.out.println(inst.addCourse("CS560"));
System.out.println(inst.addCourse("CS500"));
}
}
Simple way you can do:
For Each time executing else block so. remove else block it will work.
for(String value : courses)
{
if(courses.contains(value))
{
a=false;
break;
}
a=true;
}

Every iteration of the game I want it to reduce the life time by 1

So I have an arraylist which stores different objects about the universe (planet, comet, star etc). Instead of doing this:
planet.decreaseLifeTime(1);
star.decreaseLifeTime(1);
comet.decreaseLifeTime(1);
Every iteration of the game I want it to reduce the life time by 1. I tried this but it doesn't work:
private ArrayList<SpaceObject> universeEntities;
public void reduceLifeTime() {
for (SpaceObject entity: universeEntities) {
entity.decreaseLifeTime(1);
if(entity.getLifeTime() <= 0) {
erase(entity);
System.out.println("This entity has been erased");
}
System.out.println("life time: " + entity.getLifeTime());
}
}
Objects are added like so:
planet = new Planet(500, 500, -2, -2, 25, Color.BLUE, this);
universeEntities.add(planet);
If erase(entity) is modifying the universeEntities list java will get mad.
You can either store the SpaceObject you want to erase in a separate list and then erase them after the for loop.
or
You can loop over the universeEntities without using an iterator
e.g. a numerical index
According to your implementation of the reduceLifeTime method, the problem may be in calling erase method in it (depends how it is implemented).
If erase method just tries to remove an item from universeEntities collection by calling ArrayList's remove method it just break an iterator.
Consider reimplementing your method to:
public void reduceLifeTime() {
Iterator<SpaceObject> iterator = universeEntities.iterator();
while (iterator.hasNext()) {
SpaceObject object = iterator.next();
object.decreaseLifeTime(1);
if(object.getLifeTime() <= 0) {
iterator.remove();
System.out.println("This entity has been erased.");
}
System.out.println(String.format("Life time: %d", object.getLifeTime()));
}
}
Fully working sample:
public class Test {
private ArrayList<SpaceObject> universeEntities = new ArrayList<SpaceObject>();
public Test() {
universeEntities.add(new Planet());
universeEntities.add(new Planet());
}
public void reduceLifeTime() {
Iterator<SpaceObject> iterator = universeEntities.iterator();
while (iterator.hasNext()) {
SpaceObject object = iterator.next();
object.decreaseLifeTime(1);
if(object.getLifeTime() <= 0) {
iterator.remove();
System.out.println("This entity has been erased.");
}
System.out.println(String.format("Life time: %d", object.getLifeTime()));
}
}
public static void main(String[] args) {
Test test = new Test();
while(true) {
test.reduceLifeTime();
// Endless loop. Need a quit condition.
}
}
public static class SpaceObject {
protected int life = 0;
public SpaceObject(int life) {
this.life = life;
}
public void decreaseLifeTime(int value) {
this.life -= value;
}
public int getLifeTime() {
return life;
}
}
public static class Planet extends SpaceObject {
public Planet() {
super(10);
}
}
}
If you do not want to use iterators you can collect items that should be removed in some kind of collection, return from reduceLifeTime method and remove using removeAll afterwards.

How to filter words in Java?

I want to check if there are 'bad' words in some cases such as checking IDs in register form. But I do not know how to check it.. The bottom code is what I got far with it.
String words = "admin,administrator,babo,sir,melon";
public boolean checkWord(String input) {
if(something here that i need to find??) return false;
else return true;
}
The pattern of words are divided in comma, and I really need help with it please!
The simplest thing would be to search for a word in a sorted array, like this:
private static String[] WORDS = new String[] {
"admin", "administrator", "babo", "melon", "sir"
};
public boolean checkWord(String input) {
return Arrays.binarySearch(WORDS, input) < 0; // Not found
}
Another example if you want to look for group of words inside your input
public class TestCheckWord {
static String words = "admin,administrator,babo,sir,melon";
public static void main (String args[]){
System.out.println(checkWord("Hello melon"));
System.out.println(checkWord("Hello sir"));
System.out.println(checkWord("Hello you"));
}
public static boolean checkWord(String input) {
String wordArray[] = words.split(",");
for(int i=0; i<wordArray.length; i++){
if(input.indexOf(wordArray[i])>-1)
return true;
}
return false;
}
}
and yet even another way to look for words only if your input contains only one word.(the order in the array doesn't matter in this case.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TestCheckWord2 {
public static void main (String args[]){
System.out.println(checkWord("babo"));
System.out.println(checkWord("bobo"));
}
private static String[] WORDS = {"admin", "babo", "melon", "sir", "administrator"};
private static Set<String> mySet = new HashSet<String>(Arrays.asList(WORDS));
public static boolean checkWord(String input) {
return mySet.contains(input);
}
}
public class steve {
static boolean checkWord(String input, String words) {
if(words.contains(input)) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
String words = "admin,administrator,babo,sir,melon";
System.out.print(steve.checkWord("babo",words));
}
}

Categories

Resources