Home  >  Article  >  Java  >  Try this Overload the Queue constructor

Try this Overload the Queue constructor

PHPz
PHPzOriginal
2024-08-28 06:35:021046browse

Tente isso  Sobrecarregue o construtor de Queue

  • The project aims to improve the Queue class by adding two new constructors.

  • The first builder will create a new queue from another existing queue.

  • The second constructor will allow you to create a queue with initial values.

  • These constructors significantly improve the usability of the Queue class.

1 Create a file called QDemo2.java and copy the updated Queue class from the Try This 6-1 section into it.

2 First, add the following constructor, which builds one queue from another.

// Builds a queue from another.
Queue(Queue ob) {
putloc = ob.putloc;
getloc = ob.getloc;
q = new char[ob.q.length];
// copy elements
for(int i=getloc; i < putloc; i++)
q[i] = ob.q[i];
}

The constructor initializes putloc and getloc with values ​​from an ob object. Allocates a new array to the queue and copies the elements of ob to this new array. The new queue will be an identical copy of the original, but it will be a separate and independent object.

3 Now, add the constructor that initializes the queue from a character array, as shown here:

// Builds a queue with initial values.
Queue(char a[]) {
putloc = 0;
getloc = 0;
q = new char[a.length];
for(int i = 0; i < a.length; i++) put(a[i]);
}

This constructor creates a queue large enough to contain the characters to and then stores them in the queue.

The above is the detailed content of Try this Overload the Queue constructor. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Method OverloadingNext article:Method Overloading