How to find if items in 2 list match (but can't use direct equality) - optimization

I have this code here, to see if the items in both lists are identical:
for (final car in this.cars) {
bool found = false;
for (final car2 in garage2.cars) {
if (car2.id == car.id) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
(I previously check if the 2 list lengths are equal). Is there a way to rewrite that so that I don't have O(n2) complexity?

As an option you can override quals and hashcode methods for class Car
something like this
class Car {
int id;
// other fields
#override
bool operator ==(Object o) => o is Car && id == o.id;
#override
int get hashCode => id.hashCode;
}
and then you can use the native method listEquals, which compares for deep equality.
import 'package:flutter/foundation.dart';
bool isEqual = listEquals<Car>(cars, garage2.cars);

Related

Dart == operator and identical function does not yield true for 2 objects with same content

So I have been trying to compare two objects by their fields.
I have noticed there is no equals method in dart. But there are the identical function and the == operator.
I can't seem to understand why there is no equals method. What if I want to do this?
class Name {
String fname;
String lname;
String get firstName => this.fname;
void set firstName(String fname) => this.fname = fname;
String get lastName => this.lname;
void set lastName(String lname) => this.lname = lname;
Name({this.fname, this.lname});
#override
String toString() {
return this.firstName + " " + this.lastName;
}
bool equals(Name n2) {
return this.firstName == n2.firstName && this.lastName == n2.lastName
? true
: false;
}
}
void main(List<String> args) {
Name n1 = new Name();
n1.firstName = "James";
n1.lastName = "Bond";
Name n2 = new Name();
n2.firstName = "James";
n2.lastName = "Bond";
print(n1.equals(n2)); // true
print(identical(n1, n2)); // false
print(n1 == n2); // false
}
What can I do instead of making my own equals. Or does dart expect you to do this manually.
identical will not return true even if the first name and last name of the two objects you are comparing are the same. That's because they are not the same instances. Each instance has its own identity and own hashcode.
You could override the == operator and the hashcode. Then you will be able to compare two different instances. The Equatable-Package already does that for you so you can use the == operator two compare two different instances: https://pub.dev/packages/equatable
You can write code just like this
#override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType)
return false;
/// do smth
}
#override
int get hashCode {
}

Extract common objects from an arraylist

I have a list like shown below. Assume it has 16 Container objects in it. Each Container object is a simple bean, with fields like age, weight, height, etc. How can I create a sub-list that contains common 'Container' objects if a 'Container' object is considered equal if the weight and height are equal?
List<Container> containers = new ArrayList<Container>();
If by "common" containers you mean duplicating ones, then this code might help you:
import java.util.ArrayList;
import java.util.List;
public class CommonContainers {
public static void main(String[] args) {
List<Container> containers = new ArrayList<Container>(16);
for(int i=0; i<13; i++) {
containers.add(new Container(i, i));
}
//add a few duplicating ones
containers.add(new Container(1,1));
containers.add(new Container(5,5));
containers.add(new Container(6,6));
List<Container> sublist = new ArrayList<Container>();
for (Container c1 : containers) {
for (Container c2 : containers) {
if(c1 != c2 && c1.equals(c2)) {
sublist.add(c1);
}
}
}
for (Container c : sublist) {
System.out.println(c);
}
}
private static class Container {
private int weight;
private int height;
#Override
public String toString() {
return String.format("Container[w=%d,h=%d]", weight, height);
}
public Container(int weight, int height) {
this.weight = weight;
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + height;
result = prime * result + weight;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Container other = (Container) obj;
if (height != other.height)
return false;
if (weight != other.weight)
return false;
return true;
}
}
}
If you mean something else or need clarification, please let me know.
Thanks John Smith for giving direction on this question. I used the iterator instead and was able to make a nice solution to what I was looking for. below is the solution. Note that .equals is overriden for the Containers comparison. The technique I used will take the master list and create a sub-list while removing elements from the parent list at the same time. The solution can be called recursivly until you convert the master list into a subset of lists.
public List<Container> extractCommonSubList(
List<Container> masterContainerList) {
List<Container> subList = new ArrayList<Container>();
ListIterator<Container> iterator = masterContainerList.listIterator();
// get first item from master list and remove from master list
Container firstContainer = iterator.next();
iterator.remove();
// Add first container to sublist
subList.add(firstContainer);
while (iterator.hasNext()) {
Container container = iterator.next();
// Search for matches
if (firstContainer.equals(container)) {
// containers are a match, continue searching for matches
subList.add(container);
iterator.remove();
continue;
} else {
break;
}
}
// return common list
return subList;
}

Null pointer exception with a method call

Ok this is the code for one section of my switch statement:
case 1: {
System.out.print("Member ID: ");
int key = in.nextInt();
while(members.findItemByKey(key) == -1){
System.out.print("That is an invalid member ID!\nEnter a new one: ");
key = in.nextInt();
}
System.out.print("ISBN: ");
int book = in.nextInt();
while(books.findItemByKey(book) == -1){
System.out.println("That book is not in the system.\nPlease make a new choice: ");
book = in.nextInt();
}
while(stock.findItemByKey(book) != -1){
try {
m = members.get(members.findItemByKey(key));
t = books.get(books.findItemByKey(book));
} catch (Exception e) {
e.printStackTrace();
}
if(m.checkOut(t) == true){
stock.removeItem(t);
}
}
}
Here is the method that is calling:
public int findItemByKey(int key){
for(E e: list)
{
if(e.getKey() == key){
return findItem(e);
}
}
return -1;
}
public int findItem(E item){
if (item == null){
for (int i = 0; i < numElements; i++)
if(list[i]==null)
return i;
}else {
for( int i = 0; i < numElements; i++)
if (item.equals(list[i]))
return i;
}
return -1;
}
Ok, I know there's a lot to look at here, but here's what's happening. When I enter an invalid member ID, it functions properly and keeps asking the user for a new member ID until a valid one is entered. Now when I enter a book, regardless of whether I enter a valid or invalid book, I am getting a null pointer exception thrown by this line:
if(e.getKey() == key)
books, members, and stock are all arraylists defined the same way in my code. I don't understand why I'm having this exception thrown with books and not with the members. The classes for book and member are defined the same way, both have the same getKey method within them.
Maybe there's just too much going on in this question for anyone to be able to really see what's going on. Basically I just can't understand why I get a null pointer exception with the one and not with the other.
Edit: Decided I should post the getKey() method for each class.
public int getKey()
{
return ISBN;
}
Is the one for books
public int getKey()
{
return memberId;
}
Is the one for members.
ISBN is the identifier for books and memberId is the identifier for my members. Everything looks like it's calling the same things, but it errors for books and not for members. Just don't get it.
Either this e is null or the value returned from the statement e.getKey() is null.
You have to make sure that the list doesn't contain a null element and then their keys should also be not-null.
If you want to ignore these values being null, you can do like:
if(e!=null && e.getKey()!=null && e.getKey() == key){
//statements here.
}

How to write a custom FindElement routine in Selenium?

I'm trying to figure out how to write a custom FindElement routine in Selenium 2.0 WebDriver. The idea would be something like this:
driver.FindElement(By.Method( (ISearchContext) => {
/* examine search context logic here... */ }));
The anonymous method would examine the ISearchContext and return True if it matches; False otherwise.
I'm digging through the Selenium code, and getting a bit lost. It looks like the actual By.* logic is carried out server-side, not client side. That seems to be complicating matters.
Any suggestions?
I do a multi-staged search. I have a method that performs a try catch and then a method that gets the element. In theory you could do a try catch until instead of this way but I like this way better because of my setup.
public bool CheckUntil(IWebDriver driver, string selectorType, string selectorInfo)
{
int Timer = 160;
bool itemFound = false;
for (int i = 0; i < Timer; i++)
if(itemFound)
{
i = 0
}
else
{
Thread.Sleep(500);
if(selectorType.ToLower() == "id" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.Id(selectorInfo).Displayed)
{
itemFound = true;
}
}
else if(selectorType.ToLower() == "tagname" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.TagName(selectorInfo).Displayed)
{
itemFound = true;
}
}
}
return itemFound;
}
Here's my try catch method you can add as many different types as you want id, cssselector, xpath, tagname, classname, etc.
public bool TryCatch(IWebDriver driver, string selectorType, string selectorInfo)
{
bool ElementFound = false;
try
{
switch(selectorType)
{
case "id":
driver.FindElement(By.Id(selectorInfo);
break;
case "tagname":
driver.FindElement(By.TagName(selectorInfo);
break;
}
ElementFound = truel
}
catch
{
ElementFound = false;
}
return ElementFound;
}
Ok, I figured out how to do this. I'm leveraging driver.ExecuteScript() to run custom js on the webdriver. It looks a bit like this:
function elementFound(elem) {
var nodeType = navigator.appName == ""Microsoft Internet
Explorer"" ? document.ELEMENT_NODE : Node.ELEMENT_NODE;
if(elem.nodeType == nodeType)
{
/* Element identification logic here */
}
else { return false; }
}
function traverseElement(elem) {
if (elementFound(elem) == true) {
return elem;
}
else {
for (var i = 0; i < elem.childNodes.length; i++) {
var ret = traverseElement(elem.childNodes[i]);
if(ret != null) { return ret; }
}
}
}
return traverseElement(document);

two way mapping

Is any way, how to create two classes, which will be referenced both way and will use only one FK? This interest me in One-to-One as like as One-to-Many cases.
f.e.:
Class First: Entity
{
Second second;
}
Class Second: Entity
{
First first;
}
String TwoWayReference()
{
First Fir = new First();
Second Sec = new Second();
Fir.second = Sec; // I need it is equivalent to: Sec.first = Fir;
if (Sec.first == Fir)
return "Is any way how to do this code works and code return this string?";
else
return "Or it is impossible?"
}
simplest would be
class First : Entity
{
private Second second;
public virtual Second Second
{
get { return this.second; }
set {
if (value != null)
{
value.First = this;
this.second = value;
}
}
}
}
class Second : Entity
{
private First first;
public virtual First First
{
get { return this.first; }
set {
if (value != null && value.Second != this)
{
value.Second = this;
this.first = value;
}
}
}
}