Can not find symbol - method Size() - arraylist

I have been getting trouble with my program and can't figure out why I am getting this error which has been bugging me. Any suggestion will be of huge assistance! I don't know if i am missing something or something like that. I have correctly imported the Array Class.
private String title;
private ArrayList<Student> students;
private int courseId;
private static int courseIdList = 0;
/**
*
*/
public Course(String tile)
{
this.title = title;
courseId = courseIdList;
courseIdList++;
students = new ArrayList<Student>();
}
/**
* #param returns the title
*/
public String getTitle(String title)
{
return title;
}
/**
* #return returns the ID
*/
public int getId()
{
return courseId;
}
/**
*
*/
public void addStudent(Student students)
{
for(int i = 0; i < students.size(); i++)
{
if(students.getId() != students.get(i).getId())
{
students.add(i);
return;
}
}
}
/**
*
*/
public void removeStudent(Student students)
{
for(int i = 0; i < students.size(); i++)
{
if(students.getId() == students.get(i).getId())
{
students.remove(i);
return;
}
}
}
/**
* #return if class is above or equal to 10 then return true, else return false;
*/
public boolean isFull(Student students)
{
if(students.size() >= 30)
{
return true;
}
else
{
return false;
}
}
/**
* #returns if the class is below ten then return true, else return false
*/
public boolean cancel(Student students)
{
if( students.size() < 10)
{
return true;
}
else
{
return false;
}
}
/**
*
*/
public ArrayList<Student> getStudents()
{
return students;
}
/**
*
*/
public boolean inClass(Student students)
{
for(int i = 0; i < students.size(); i++)
{
if(student.getId() == students.get(i).getId())
{
return true;
}
}
return false;
}
/**
* boolean returns true if a student's ID mathes and false if their ID does not.
*/
public boolean equals(Student s)
{
if(this.getId() == s.getId())
{
return true;
}
return false;
}
/**
*
*/
public double getAverage()
{
double sum = 0;
for(Student s : students)
{
sum += s.getGrade();
}
double avg = sum / students.size();
return avg;
}
/**
*
*/
public void getHighestGrade()
{
int highestGrade = 0;
for(Student s : students)
{
if(students.getGrade() > s.get(i).getGrade())
{
students.highestGrade(i);
}
}
return new Student(" ", 0,0);
}
/**
*
*/
public ArrayList<Student> getWarnings()
{
for(i = 0; i < students.size; i++)
{
if (students.getGrade() <= 70)
{
return students;
}
}
}
/**
*
*/
public void removeSeniors(Student students)
{
for(i = 0; i < students.size; i++)
{
if(students.getId() == students.get(i).subString(0,2).equalsTo(17))
{
students.remove(i);
}
}
}
/**
*
*/
public void sortByGrade()
{
}
/**
*
*/
public void sortByAlpha()
{
}
/**
*
*/
public String toString()
{
String printOut = "";
printOut += "Course name: " + title + "\nStudent ID: " + courseId;
return printOut;
for(Student students : students)
{
printOut += students.toString() + "\n";
}
}
}

Now its the opposite :) students is a List and not a Student. You need to loop over the list and process each student.
public void doSomething(List<Student> students) {
// does not work because students is a List of students not a student.
students.getId(); // ERROR
// loop over the list and then get the id of a single student
for(Student student : students) {
int id = student.getId();
// do something with the id
}
}
size() is a method of the List interface
getId() is a method of your Student class.

Related

Syntax Error - line 0, col 122: Error: Expected end of string, got 'ON'

I'm trying to use ON in my Query Builder but it returns [Syntax Error] line 0, col 122: Error: Expected end of string, got 'ON'.
Code:
public function filterChamados(Request $request)
{
$em = $this->getDoctrine()->getManager()->getRepository(Chamados::class)
->createQueryBuilder('c')->select('c.id, d.name_fantasy, c.status, c.titulo, c.description')
->join(Clients::class, 'd',Join::ON,'c.id_client = d.id');
if ($request->request->get('status')) {
$em->where('c.status = :status')
->setParameter('status', $request->request->get('status'));
};
if (strtoupper(trim($request->get('client')))) {
$em->andWhere('(d.name_fantasy=:client OR d.razao_social=:client)')
->setParameter('client', strtoupper(trim($request->get('client'))));
};
if ($request->get('open_date')) {
$em->andWhere('c.open_date >=:open_date')
->setParameter('open_date', $request->get('open_date'));
}
if ($request->get('close_date')) {
$em->andWhere('c.close_date <=:close_date')
->setParameter('close_date', $request->get('close_date'));
}
$em->getQuery()->getArrayResult();
return new JsonResponse($em);
}
If I return its DQL, I get:
SELECT c.id, d.name_fantasy, c.status, c.titulo, c.description FROM App\Entity\Chamados c INNER JOIN App\Entity\Clients d ON c.id_client = d.id WHERE (d.name_fantasy=:client OR d.razao_social=:client)
If I run the SQL directly into PGAdmin, it works.
If I change ON to WITH, it does not return errors, but the result comes empty. Plus, I can't run its SQL directly into PGAdmin.
What am I doing wrong?
EDIT:
This is my raw SQL (considering I'm using all fields):
SELECT
c.id, d.name_fantasy, c. status, c.titulo, c.description
FROM
chamados c
JOIN
clients d
ON
c.id_client_id = d.id
WHERE
c.status = 2 --:status
AND
(d.name_fantasy = 'FARMÁCIA ALGUMA COISA' OR d.razao_social = 'FARMÁCIA ALGUMA COISA') -- :client
AND
c.open_date >= '2019-03-03 10:00' --:open_date
AND
c.close_date <= '2019-09-03 18:00' --:close_date
Entity Chamados:
/**
* #ORM\Entity(repositoryClass="App\Repository\ChamadosRepository")
*/
class Chamados
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $titulo;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Clients", inversedBy="chamados")
* #ORM\JoinColumn(nullable=false)
*/
private $id_client;
/**
* #ORM\Column(type="integer", options={"default" = 0})
*/
private $status;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="chamados")
*/
private $user;
/**
* #ORM\Column(type="datetime")
*/
private $open_date;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $update_date;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $close_date;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Tramite", mappedBy="chamado")
*/
private $tramites;
public function __construct()
{
$this->user = new ArrayCollection();
$this->tramites = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getIdClient(): ?Clients
{
return $this->id_client;
}
public function setIdClient(?Clients $id_client): self
{
$this->id_client = $id_client;
return $this;
}
public function getStatus(): ?int
{
return $this->status;
}
public function setStatus(int $status): self
{
$this->status = $status;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
/**
* #return Collection|User[]
*/
public function getUser(): Collection
{
return $this->user;
}
public function addUser(User $user): self
{
if (!$this->user->contains($user)) {
$this->user[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->user->contains($user)) {
$this->user->removeElement($user);
}
return $this;
}
public function getOpenDate(): ?DateTimeInterface
{
return $this->open_date;
}
public function setOpenDate(DateTimeInterface $open_date): self
{
$this->open_date = $open_date;
return $this;
}
public function getUpdateDate(): ?DateTimeInterface
{
return $this->update_date;
}
public function setUpdateDate(?DateTimeInterface $update_date): self
{
$this->update_date = $update_date;
return $this;
}
public function getCloseDate(): ?DateTimeInterface
{
return $this->close_date;
}
public function setCloseDate(?DateTimeInterface $close_date): self
{
$this->close_date = $close_date;
return $this;
}
/**
* #return mixed
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* #param mixed $titulo
* #return Chamados
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* #return Collection|Tramite[]
*/
public function getTramites(): Collection
{
return $this->tramites;
}
public function addTramite(Tramite $tramite): self
{
if (!$this->tramites->contains($tramite)) {
$this->tramites[] = $tramite;
$tramite->setChamado($this);
}
return $this;
}
public function removeTramite(Tramite $tramite): self
{
if ($this->tramites->contains($tramite)) {
$this->tramites->removeElement($tramite);
// set the owning side to null (unless already changed)
if ($tramite->getChamado() === $this) {
$tramite->setChamado(null);
}
}
return $this;
}
}
Entity Clients:
/**
* #ORM\Entity(repositoryClass="App\Repository\ClientsRepository")
*/
class Clients
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name_fantasy;
/**
* #ORM\Column(type="string", length=255)
*/
private $razao_social;
/**
* #ORM\Column(type="string", length=128, nullable=true)
*/
private $contact_email;
/**
* #ORM\Column(type="string", length=16, nullable=true)
*/
private $contact_telephone;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Chamados", mappedBy="id_client")
*/
private $chamados;
/**
* #ORM\Column(type="boolean", options={"default"="true"})
*/
private $active;
public function __construct()
{
$this->chamados = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNameFantasy(): ?string
{
return $this->name_fantasy;
}
public function setNameFantasy(string $name_fantasy): self
{
$this->name_fantasy = mb_convert_case($name_fantasy, MB_CASE_UPPER, 'UTF-8');
return $this;
}
public function getRazaoSocial(): ?string
{
return $this->razao_social;
}
public function setRazaoSocial(string $razao_social): self
{
$this->razao_social = mb_convert_case($razao_social, MB_CASE_UPPER, 'UTF-8');
return $this;
}
public function getContactEmail(): ?string
{
return $this->contact_email;
}
public function setContactEmail(?string $contact_email): self
{
$this->contact_email = $contact_email;
return $this;
}
public function getContactTelephone(): ?string
{
return $this->contact_telephone;
}
public function setContactTelephone(?string $contact_telephone): self
{
$this->contact_telephone = $contact_telephone;
return $this;
}
/**
* #return Collection|Chamados[]
*/
public function getChamados(): Collection
{
return $this->chamados;
}
public function addChamado(Chamados $chamado): self
{
if (!$this->chamados->contains($chamado)) {
$this->chamados[] = $chamado;
$chamado->setIdClient($this);
}
return $this;
}
public function removeChamado(Chamados $chamado): self
{
if ($this->chamados->contains($chamado)) {
$this->chamados->removeElement($chamado);
// set the owning side to null (unless already changed)
if ($chamado->getIdClient() === $this) {
$chamado->setIdClient(null);
}
}
return $this;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
* #return Clients
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
}
Edit 2:
The error is gone and the query is being built properly, but the result is empty.
Controller:
public function filterChamados(Request $request)
{
$em = $this->getDoctrine()->getManager()->getRepository(Chamados::class)
->createQueryBuilder('c')->select('c.id, d.name_fantasy, c.status, c.titulo, c.description')
->join('c.id_client', 'd');
if ($request->request->get('status')) {
$em->where('c.status = :status')
->setParameter('status', $request->request->get('status'));
}
if (strtoupper(trim($request->get('client')))) {
$em->andWhere('(d.name_fantasy=:client OR d.razao_social=:client)')
->setParameter('client', strtoupper(trim($request->get('client'))));
}
if ($request->get('open_date')) {
$em->andWhere('c.open_date >=:open_date')
->setParameter('open_date', $request->get('open_date'));
}
if ($request->get('close_date')) {
$em->andWhere('c.close_date <=:close_date')
->setParameter('close_date', $request->get('close_date'));
}
$em->getQuery()->getArrayResult();
return new JsonResponse($em);
}
Generated query:
[2019-08-21 17:22:31] doctrine.DEBUG: SELECT c0_.id AS id_0, c1_.name_fantasy AS name_fantasy_1, c0_.status AS status_2, c0_.titulo AS titulo_3, c0_.description AS description_4 FROM chamados c0_ INNER JOIN clients c1_ ON c0_.id_client_id = c1_.id WHERE (c1_.name_fantasy = ? OR c1_.razao_social = ?) ["PADARIA","PADARIA"] []
PgAdmin3: If I put both values inside the query and replace " by ', it works, otherwise it returns column "PADARIA" does not exist.
Inside AJAX request: it returns an empty JSON.
For some reason you have a semicolon where it should not be, try the following function, not saying it will work though:
function filterChamados(Request $request)
{
$em = $this->getDoctrine()->getManager()->getRepository(Chamados::class)
->createQueryBuilder('c')->select('c.id, d.name_fantasy, c.status, c.titulo, c.description')
->join('c.Clients', 'd', Join::ON, 'c.id_client = d.id');
if ($request->request->get('status')) {
$em->where('c.status = :status')
->setParameter('status', $request->request->get('status'));
}
if (strtoupper(trim($request->get('client')))) {
$em->andWhere('(d.name_fantasy=:client OR d.razao_social=:client)')
->setParameter('client', strtoupper(trim($request->get('client'))));
}
if ($request->get('open_date')) {
$em->andWhere('c.open_date >=:open_date')
->setParameter('open_date', $request->get('open_date'));
}
if ($request->get('close_date')) {
$em->andWhere('c.close_date <=:close_date')
->setParameter('close_date', $request->get('close_date'));
}
$em->getQuery()->getArrayResult();
return new JsonResponse($em);
}
Notice how I have removed the semicolon from the following pieces of code:
if ($request->request->get('status')) {
$em->where('c.status = :status')
->setParameter('status', $request->request->get('status'));
};
if (strtoupper(trim($request->get('client')))) {
$em->andWhere('(d.name_fantasy=:client OR d.razao_social=:client)')
->setParameter('client', strtoupper(trim($request->get('client'))));
};
Also notice how I have change the JOIN:
->join('c.Clients', 'd', Join::ON, 'c.id_client = d.id');
UPDATE:
Change this:
if(strtoupper(trim($request->get('client')))) {
$client = strtoupper(trim($request->get('client')));
$em->andWhere('d.name_fantasy=:client')
->orWhere('d.razao_social=:client')
->setParameter('client', $client);
}
Or:
if (strtoupper(trim($request->get('client')))) {
$em->andWhere('d.name_fantasy=:client OR d.razao_social=:client')
->setParameter('client', strtoupper(trim($request->get('client'))));
};
More info here.

Generic BST having trouble getting constructor to work

I have been given some code from my instructor and i need to implement several functions. I have added the insert method but I can not figure out how or what the constructor is looking for, I don't understand why this call to construct a tree is not working. Not very strong in java but understand the logic of a BST
public class BinaryTreeDriver {
public static void main(String[] args){
BinaryTree<Integer> numbers = new BinaryTree<>();
I am getting compiler error cannot infer type arguments BinaryTree<>
Copying rest of code below
public class BinaryTree<T extends Comparable<T>> {
private BinaryTreeNode<T> root; // the root of the tree
private BinaryTreeNode<T> cursor; // the current node
/**
* Constructor for initializing a tree with node
* being set as the root of the tree.
* #param node
*/
public BinaryTree(BinaryTreeNode<T> node) {
root = node;
}
/**
* Moves the cursor to the root.
*/
public void toRoot() {
cursor = root;
}
/**
* Returns the cursor node.
* #return cursor
*/
public BinaryTreeNode<T> getCursor() {
return cursor;
}
/**
* Sets the root to the provided node.
* ONLY USE IN THE DELETE METHOD
* #param node
*/
public void setRoot(BinaryTreeNode<T> node) {
root = node;
}
/**
* Checks if the tree node has a left child node
* #return true if left child exists else false
*/
public boolean hasLeftChild() {
return cursor.getLeft() != null;
}
/**
* Checks if the tree node has a right child node
* #return true if right child exists else false
*/
public boolean hasRightChild() {
return cursor.getRight() != null;
}
/**
* Move the cursor to the left child
*/
public void toLeftChild() {
cursor = cursor.getLeft();
}
/**
* Move the cursor to the right child
*/
public void toRightChild() {
cursor = cursor.getRight();
}
/**
* #return height of the tree
*/
public int height() {
if (root != null) {
return root.height();
} else {
return 0;
}
}
**/**
* Tree-Insert
*/
public boolean insert(T elem)
{
return insert(root, elem);
}
public boolean insert(BinaryTreeNode start, T elem)
{
if (start == null)
{
root = new BinaryTreeNode<T>(elem, null, null);
return true;
}
int comparison = start.getData().compareTo(elem);
if (comparison > 0)
{
if (start.getLeft() == null)
{
start.setLeft(new BinaryTreeNode(elem, null, null));
return true;
}
return insert(start.getLeft(), elem);
}
else if (comparison < 0)
{
if (start.getRight() == null)
{
start.setRight(new BinaryTreeNode(elem, null, null));
return true;
}
return insert(start.getRight(), elem);
}
else
{
return false;
}**
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
public String toString() {
if (root != null) {
return root.toStringPreOrder(".");
} else {
return "";
}
}
}
public class BinaryTreeNode<T extends Comparable<T>> {
private BinaryTreeNode<T> left; // the left child
private BinaryTreeNode<T> right; // the right child
private T data; // the data in this node
public BinaryTreeNode() {
this(null, null, null);
}
public BinaryTreeNode(T theData) {
this(theData, null, null);
}
public BinaryTreeNode(T theData, BinaryTreeNode<T> leftChild,
BinaryTreeNode<T> rightChild) {
data = theData;
left = leftChild;
right = rightChild;
}
public T getData() {
return data;
}
public BinaryTreeNode<T> getLeft() {
return left;
}
public BinaryTreeNode<T> getRight() {
return right;
}
public void setLeft(BinaryTreeNode<T> newLeft) {
left = newLeft;
}
public void setRight(BinaryTreeNode<T> newRight) {
right = newRight;
}
public void setData(T newData) {
data = newData;
}
public void preOrder() {
System.out.println(data);
if (left != null) {
left.preOrder();
}
if (right != null) {
right.preOrder();
}
}
public int height() {
int leftHeight = 0; // Height of the left subtree
int rightHeight = 0; // Height of the right subtree
int height = 0; // The height of this subtree
// If we have a left subtree, determine its height
if (left != null) {
leftHeight = left.height();
}
// If we have a right subtree, determine its height
if (right != null) {
rightHeight = right.height();
}
// The height of the tree rooted at this node is one more than the
// height of the 'taller' of its children.
if (leftHeight > rightHeight) {
height = 1 + leftHeight;
} else {
height = 1 + rightHeight;
}
// Return the answer
return height;
}
/**
* #param pathString
* #return the tree nodes in pre-order traversal
*/
public String toStringPreOrder(String pathString) {
String treeString = pathString + " : " + data + "\n";
if (left != null) {
treeString += left.toStringPreOrder(pathString + "L");
}
if (right != null) {
treeString += right.toStringPreOrder(pathString + "R");
}
return treeString;
}
}

How to deserialize a JSON array to a singly linked list by using Jackson

I want to deserialize a JSON array to a singly linked list in Java.
The definition of singly linked list is as the following:
public class SinglyLinkedListNode<T> {
public T value;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(final T value) {
this.value = value;
}
}
How to deserialize a JSON string such as [1,2,3,4,5] in to a singly linked list?
public void typeReferenceTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final ArrayList<Integer> intArray = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<ArrayList<Integer>>() {});
System.out.println(intArray);
// How to achieve this?
final ArrayList<Integer> intList = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<SinglyLinkedListNode<Integer>>() {});
System.out.println(intList);
}
Moreover, I want the SinglyLinkedListNode to be a first-class citizen the same as ArrayList, which can be used in all kinds of combinations, such as HashSet<SinglyLinkedListNode<Integer>>, SinglyLinkedListNode<HashMap<String, Integer>>.
For example, what happens if I want to deserialize [[1,2,3], [4,5,6]] into a ArrayList<SinglyLinkedListNode<Integer>> ?
As far as I know, a customized deserializer extending JsonDeserializer is not enough to do this.
When you want it to be deserialized to ArrayList<SinglyLinkedListNode<Integer>> for example. Your code specifies that is the type that expected. Therefore it should if a deserializer for SinglyLinkedListNode<Integer> is regeistered it will succeed.
From the jackson-user google group I get the right answer from #Tatu Saloranta.
The answer is simple: just implement the java.util.List interface, and Jackson will automatically serialize/deserialize between JSON array and SinglyLinkedListNode.
So I implement the java.util.List interface for SinglyLinkedListNode, the code is as the following:
import java.util.*;
import java.util.function.Consumer;
/**
* Singly Linked List.
*
* <p>As to singly linked list, a node can be viewed as a single node,
* and it can be viewed as a list too.</p>
*
* #param <E> the type of elements held in this collection
* #see java.util.LinkedList
*/
public class SinglyLinkedListNode<E>
extends AbstractSequentialList<E>
implements Cloneable, java.io.Serializable {
public E value;
public SinglyLinkedListNode<E> next;
/**
* Constructs an empty list.
*/
public SinglyLinkedListNode() {
value = null;
next = null;
}
/**
* Constructs an list with one elment.
*/
public SinglyLinkedListNode(final E value) {
this.value = value;
next = null;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* #param c the collection whose elements are to be placed into this list
* #throws NullPointerException if the specified collection is null
*/
public SinglyLinkedListNode(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final SinglyLinkedListNode<E> l = last();
final SinglyLinkedListNode<E> newNode = new SinglyLinkedListNode<>(e);
if (l == null)
this.value = e;
else
l.next = newNode;
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, SinglyLinkedListNode<E> succ) {
assert succ != null;
final SinglyLinkedListNode<E> prev = this.previous(succ);
final SinglyLinkedListNode<E> newNode = new SinglyLinkedListNode<>(e);
if (prev == null)
this.value = e;
else
prev.next = newNode;
modCount++;
}
/**
* Return the node before x.
*
* #param x current node
* #return the node before x
*/
private SinglyLinkedListNode<E> previous(final SinglyLinkedListNode<E> x) {
assert (x != null);
if (size() < 2) return null;
if (this == x) return null;
SinglyLinkedListNode<E> prev = new SinglyLinkedListNode<>();
prev.next = this;
SinglyLinkedListNode<E> cur = this;
while (cur != x) {
prev = prev.next;
cur = cur.next;
}
return prev;
}
/**
* Return the last node.
* #return the last node.
*/
private SinglyLinkedListNode<E> last() {
if (size() == 0) return null;
if (size() == 1) return this;
SinglyLinkedListNode<E> prev = new SinglyLinkedListNode<>();
prev.next = this;
SinglyLinkedListNode<E> cur = this;
while (cur != null) {
prev = prev.next;
cur = cur.next;
}
return prev;
}
/**
* Unlinks non-null node x.
*/
E unlink(SinglyLinkedListNode<E> x) {
assert x != null;
final E element = x.value;
final SinglyLinkedListNode<E> next = x.next;
final SinglyLinkedListNode<E> prev = previous(x);
if (prev == null) {
this.value = next.value;
this.next = next.next;
} else {
prev.next = next;
}
x.next = null;
modCount++;
return element;
}
/**
* #inheritDoc
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private SinglyLinkedListNode<E> lastReturned;
private SinglyLinkedListNode<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
assert isPositionIndex(index);
next = (index == size()) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size();
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.value;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
throw new UnsupportedOperationException();
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
unlink(lastReturned);
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.value = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size()) {
action.accept(next.value);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* #inheritDoc
*/
public int size() {
int size = 0;
if (value == null) return size;
SinglyLinkedListNode<E> cur = this;
while (cur != null) {
size++;
cur = cur.next;
}
return size;
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Returns the (non-null) Node at the specified element index.
*/
SinglyLinkedListNode<E> node(int index) {
assert isElementIndex(index);
SinglyLinkedListNode<E> x = this;
for (int i = 0; i < index; i++)
x = x.next;
return x;
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size();
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size();
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: " + size();
}
}
Here is the unit test code:
#Test public void typeReferenceTest() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final SinglyLinkedListNode<Integer> intList = objectMapper.readValue("[1,2,3,4,5]",
new TypeReference<SinglyLinkedListNode<Integer>>() {});
System.out.println(intList);
final ArrayList<SinglyLinkedListNode<Integer>> arrayOfList = objectMapper.readValue("[[1,2,3], [4,5,6]]",
new TypeReference<ArrayList<SinglyLinkedListNode<Integer>>>() {});
System.out.println(arrayOfList);
}
#Tatu Saloranta Thank you very much!
Here is my original blog, Deserialize a JSON Array to a Singly Linked List

SQL "VIEW" in codeigniter

I want to create an SQL view within the codeigniter model. What is the best way of doing this?
I use mutliple models depending on wich table i need to work
application/core/MY_model.php
<?php
/**
* CRUD Model
* A base model providing CRUD, pagination and validation.
*/
class MY_Model extends CI_Model
{
public $table;
public $primary_key;
public $default_limit = 15;
public $page_links;
public $query;
public $form_values = array();
protected $default_validation_rules = 'validation_rules';
protected $validation_rules;
public $validation_errors;
public $total_rows;
public $date_created_field;
public $date_modified_field;
public $native_methods = array(
'select', 'select_max', 'select_min', 'select_avg', 'select_sum', 'join',
'where', 'or_where', 'where_in', 'or_where_in', 'where_not_in', 'or_where_not_in',
'like', 'or_like', 'not_like', 'or_not_like', 'group_by', 'distinct', 'having',
'or_having', 'order_by', 'limit'
);
function __construct()
{
parent::__construct();
}
public function __call($name, $arguments)
{
call_user_func_array(array($this->db, $name), $arguments);
return $this;
}
/**
* Sets CI query object and automatically creates active record query
* based on methods in child model.
* $this->model_name->get()
*/
public function get($with = array(), $include_defaults = true)
{
if ($include_defaults) {
$this->set_defaults();
}
foreach ($with as $method) {
$this->$method();
}
$this->query = $this->db->get($this->table);
return $this;
}
/**
* Query builder which listens to methods in child model.
* #param type $exclude
*/
private function set_defaults($exclude = array())
{
$native_methods = $this->native_methods;
foreach ($exclude as $unset_method) {
unset($native_methods[array_search($unset_method, $native_methods)]);
}
foreach ($native_methods as $native_method) {
$native_method = 'default_' . $native_method;
if (method_exists($this, $native_method)) {
$this->$native_method();
}
}
}
/**
* Call when paginating results.
* $this->model_name->paginate()
*/
public function paginate($with = array())
{
$uri_segment = '';
$offset = 0;
$per_page = $this->default_limit;
$this->load->helper('url');
$this->load->library('pagination');
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->total_rows = $this->db->count_all_results($this->table);
$uri_segments = $this->uri->segment_array();
foreach ($uri_segments as $key => $segment) {
if ($segment == 'page') {
$uri_segment = $key + 1;
if (isset($uri_segments[$uri_segment])) {
$offset = $uri_segments[$uri_segment];
}
unset($uri_segments[$key], $uri_segments[$key + 1]);
$base_url = site_url(implode('/', $uri_segments) . '/page/');
}
}
if (!$uri_segment) {
$base_url = site_url($this->uri->uri_string() . '/page/');
}
$config = array(
'base_url' => $base_url,
'uri_segment' => $uri_segment,
'total_rows' => $this->total_rows,
'per_page' => $per_page
);
if ($this->config->item('pagination_style')) {
$config = array_merge($config, $this->config->item('pagination_style'));
}
$this->pagination->initialize($config);
$this->page_links = $this->pagination->create_links();
/**
* Done with pagination, now on to the paged results
*/
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->db->limit($per_page, $offset);
$this->query = $this->db->get($this->table);
return $this;
}
function paginate_api($limit, $offset)
{
$this->set_defaults();
if (empty($limit)) {
$limit = $this->default_limit;
}
if (empty($offset)) {
$offset = 0;
}
$this->db->limit($limit, $offset);
return $this->db->get($this->table)->result();
}
/**
* Retrieves a single record based on primary key value.
*/
public function get_by_id($id, $with = array())
{
foreach ($with as $method) {
$this->$method();
}
return $this->where($this->primary_key, $id)->get()->row();
}
public function save($id = NULL, $db_array = NULL)
{
if (!$db_array) {
$db_array = $this->db_array();
}
if (!$id) {
if ($this->date_created_field) {
$db_array[$this->date_created_field] = time();
}
$this->db->insert($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully created.');
return $this->db->insert_id();
} else {
if ($this->date_modified_field) {
$db_array[$this->date_modified_field] = time();
}
$this->db->where($this->primary_key, $id);
$this->db->update($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully updated.');
return $id;
}
}
/**
* Returns an array based on $_POST input matching the ruleset used to
* validate the form submission.
*/
public function db_array()
{
$db_array = array();
$validation_rules = $this->{$this->validation_rules}();
foreach ($this->input->post() as $key => $value) {
if (array_key_exists($key, $validation_rules)) {
$db_array[$key] = $value;
}
}
return $db_array;
}
/**
* Deletes a record based on primary key value.
* $this->model_name->delete(5);
*/
public function delete($id, $others = array())
{
if (!empty($others)) {
foreach ($others as $k => $v) {
$this->db->where($k, $v);
}
} else {
$this->db->where($this->primary_key, $id);
}
return $this->db->delete($this->table);
// $this->session->set_flashdata('alert_success', 'Record successfully deleted.');
}
/**
* Returns the CI query result object.
* $this->model_name->get()->result();
*/
public function result()
{
return $this->query->result();
}
/**
* Returns the CI query row object.
* $this->model_name->get()->row();
*/
public function row()
{
return $this->query->row();
}
/**
* Returns CI query result array.
* $this->model_name->get()->result_array();
*/
public function result_array()
{
return $this->query->result_array();
}
/**
* Returns CI query row array.
* $this->model_name->get()->row_array();
*/
public function row_array()
{
return $this->query->row_array();
}
/**
* Returns CI query num_rows().
* $this->model_name->get()->num_rows();
*/
public function num_rows()
{
return $this->query->num_rows();
}
/**
* Used to retrieve record by ID and populate $this->form_values.
* #param int $id
*/
public function prep_form($id = NULL)
{
if (!$_POST and ($id)) {
$this->db->where($this->primary_key, $id);
$row = $this->db->get($this->table)->row();
foreach ($row as $key => $value) {
$this->form_values[$key] = $value;
}
}
}
/**
* Performs validation on submitted form. By default, looks for method in
* child model called validation_rules, but can be forced to run validation
* on any method in child model which returns array of validation rules.
* #param string $validation_rules
* #return boolean
*/
public function run_validation($validation_rules = NULL)
{
if (!$validation_rules) {
$validation_rules = $this->default_validation_rules;
}
foreach (array_keys($_POST) as $key) {
$this->form_values[$key] = $this->input->post($key);
}
if (method_exists($this, $validation_rules)) {
$this->validation_rules = $validation_rules;
$this->load->library('form_validation');
$this->form_validation->set_rules($this->$validation_rules());
$run = $this->form_validation->run();
$this->validation_errors = validation_errors();
return $run;
}
}
/**
* Returns the assigned form value to a form input element.
* #param type $key
* #return type
*/
public function form_value($key)
{
return (isset($this->form_values[$key])) ? $this->form_values[$key] : '';
}
}
then when i need a model for a specific database i use class inside models
models/content.php
class content_types extends MY_Model
{
function __construct()
{
parent::__construct();
$this->curentuserdata = $this->session->userdata('lg_result');
$this->userprofile = $this->session->userdata('user_profile');
}
public $table = 'content_types';
public $primary_key = 'id';
public $default_limit = 50;
public function default_order_by()
{
$this->db->order_by('id asc');
}
}
then where i need to call the model
$this->modelname->save($id,array());
$this->modelname->where()->get()->row();
so create one for the 'view table' and the others for insert tables

Exporting a non public Type through public API

I am trying to follow Trees tutorial at: http://cslibrary.stanford.edu/110/BinaryTrees.html
Here is the code I have written so far:
package trees.bst;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* #author sachin
*/
public class BinarySearchTree {
Node root = null;
class Node {
Node left = null;
Node right = null;
int data = 0;
public Node(int data) {
this.left = null;
this.right = null;
this.data = data;
}
}
public void insert(int data) {
root = insert(data, root);
}
public boolean lookup(int data) {
return lookup(data, root);
}
public void buildTree(int numNodes) {
for (int i = 0; i < numNodes; i++) {
int num = (int) (Math.random() * 10);
System.out.println("Inserting number:" + num);
insert(num);
}
}
public int size() {
return size(root);
}
public int maxDepth() {
return maxDepth(root);
}
public int minValue() {
return minValue(root);
}
public int maxValue() {
return maxValue(root);
}
public void printTree() { //inorder traversal
System.out.println("inorder traversal:");
printTree(root);
System.out.println("\n--------------");
}
public void printPostorder() { //inorder traversal
System.out.println("printPostorder traversal:");
printPostorder(root);
System.out.println("\n--------------");
}
public int buildTreeFromOutputString(String op) {
root = null;
int i = 0;
StringTokenizer st = new StringTokenizer(op);
while (st.hasMoreTokens()) {
String stNum = st.nextToken();
int num = Integer.parseInt(stNum);
System.out.println("buildTreeFromOutputString: Inserting number:" + num);
insert(num);
i++;
}
return i;
}
public boolean hasPathSum(int pathsum) {
return hasPathSum(pathsum, root);
}
public void mirror() {
mirror(root);
}
public void doubleTree() {
doubleTree(root);
}
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.getRoot());
}
public void printPaths() {
if (root == null) {
System.out.println("print path sum: tree is empty");
}
List pathSoFar = new ArrayList();
printPaths(root, pathSoFar);
}
///-------------------------------------------Public helper functions
public Node getRoot() {
return root;
}
//Exporting a non public Type through public API
///-------------------------------------------Helper Functions
private boolean isLeaf(Node node) {
if (node == null) {
return false;
}
if (node.left == null && node.right == null) {
return true;
}
return false;
}
///-----------------------------------------------------------
private boolean sameTree(Node n1, Node n2) {
if ((n1 == null && n2 == null)) {
return true;
} else {
if ((n1 == null || n2 == null)) {
return false;
} else {
if ((n1.data == n2.data)) {
return (sameTree(n1.left, n2.left) && sameTree(n1.right, n2.right));
}
}
}
return false;
}
private void doubleTree(Node node) {
//create a copy
//bypass the copy to continue looping
if (node == null) {
return;
}
Node copyNode = new Node(node.data);
Node temp = node.left;
node.left = copyNode;
copyNode.left = temp;
doubleTree(copyNode.left);
doubleTree(node.right);
}
private void mirror(Node node) {
if (node == null) {
return;
}
Node temp = node.left;
node.left = node.right;
node.right = temp;
mirror(node.left);
mirror(node.right);
}
private void printPaths(Node node, List pathSoFar) {
if (node == null) {
return;
}
pathSoFar.add(node.data);
if (isLeaf(node)) {
System.out.println("path in tree:" + pathSoFar);
pathSoFar.remove(pathSoFar.lastIndexOf(node.data)); //only the current node, a node.data may be duplicated
return;
} else {
printPaths(node.left, pathSoFar);
printPaths(node.right, pathSoFar);
}
}
private boolean hasPathSum(int pathsum, Node node) {
if (node == null) {
return false;
}
int val = pathsum - node.data;
boolean ret = false;
if (val == 0 && isLeaf(node)) {
ret = true;
} else if (val == 0 && !isLeaf(node)) {
ret = false;
} else if (val != 0 && isLeaf(node)) {
ret = false;
} else if (val != 0 && !isLeaf(node)) {
//recurse further
ret = hasPathSum(val, node.left) || hasPathSum(val, node.right);
}
return ret;
}
private void printPostorder(Node node) { //inorder traversal
if (node == null) {
return;
}
printPostorder(node.left);
printPostorder(node.right);
System.out.print(" " + node.data);
}
private void printTree(Node node) { //inorder traversal
if (node == null) {
return;
}
printTree(node.left);
System.out.print(" " + node.data);
printTree(node.right);
}
private int minValue(Node node) {
if (node == null) {
//error case: this is not supported
return -1;
}
if (node.left == null) {
return node.data;
} else {
return minValue(node.left);
}
}
private int maxValue(Node node) {
if (node == null) {
//error case: this is not supported
return -1;
}
if (node.right == null) {
return node.data;
} else {
return maxValue(node.right);
}
}
private int maxDepth(Node node) {
if (node == null || (node.left == null && node.right == null)) {
return 0;
}
int ldepth = 1 + maxDepth(node.left);
int rdepth = 1 + maxDepth(node.right);
if (ldepth > rdepth) {
return ldepth;
} else {
return rdepth;
}
}
private int size(Node node) {
if (node == null) {
return 0;
}
return 1 + size(node.left) + size(node.right);
}
private Node insert(int data, Node node) {
if (node == null) {
node = new Node(data);
} else if (data <= node.data) {
node.left = insert(data, node.left);
} else {
node.right = insert(data, node.right);
}
//control should never reach here;
return node;
}
private boolean lookup(int data, Node node) {
if (node == null) {
return false;
}
if (node.data == data) {
return true;
}
if (data < node.data) {
return lookup(data, node.left);
} else {
return lookup(data, node.right);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
int treesize = 5;
bst.buildTree(treesize);
//treesize = bst.buildTreeFromOutputString("4 4 4 6 7");
treesize = bst.buildTreeFromOutputString("3 4 6 3 6");
//treesize = bst.buildTreeFromOutputString("10");
for (int i = 0; i < treesize; i++) {
System.out.println("Searching:" + i + " found:" + bst.lookup(i));
}
System.out.println("tree size:" + bst.size());
System.out.println("maxDepth :" + bst.maxDepth());
System.out.println("minvalue :" + bst.minValue());
System.out.println("maxvalue :" + bst.maxValue());
bst.printTree();
bst.printPostorder();
int pathSum = 10;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
pathSum = 6;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
pathSum = 19;
System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum));
bst.printPaths();
bst.printTree();
//bst.mirror();
System.out.println("Tree after mirror function:");
bst.printTree();
//bst.doubleTree();
System.out.println("Tree after double function:");
bst.printTree();
System.out.println("tree size:" + bst.size());
System.out.println("Same tree:" + bst.sameTree(bst));
BinarySearchTree bst2 = new BinarySearchTree();
bst2.buildTree(treesize);
treesize = bst2.buildTreeFromOutputString("3 4 6 3 6");
bst2.printTree();
System.out.println("Same tree:" + bst.sameTree(bst2));
System.out.println("---");
}
}
Now the problem is that netbeans shows Warning: Exporting a non public Type through public API for function getRoot().
I write this function to get root of tree to be used in sameTree() function, to help comparison of "this" with given tree.
Perhaps this is a OOP design issue... How should I restructure the above code that I do not get this warning and what is the concept I am missing here?
The issue here is that some code might call getRoot() but won't be able to use it's return value since you only gave package access to the Node class.
Make Node a top level class with its own file, or at least make it public
I don't really understand why you even created the getRoot() method. As long as you are inside your class you can even access private fields from any other object of the same class.
So you can change
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.getRoot());
}
to
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
return sameTree(this.root, bst.root);
}
I would also add a "short path" for the case you pass the same instance to this method:
public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree?
if (this == bst) {
return true;
}
return sameTree(this.root, bst.root);
}