#java #generics
#java #общие
Вопрос:
Я получаю эту ошибку, вот необходимый код. Предположим, что методы здесь не работают правильно. Любая помощь была бы потрясающей. (Кстати, я кодирую текстовый файл в Ubuntu)
Вот сообщение об ошибке: (после компиляции)
BinarySearchTree.Ява:132: ошибка: несовместимые типы: int не может быть преобразован в T вставьте(г); ^ где T-это тип переменной: Т простирается сопоставимых<? super T> объявлено в классе BinarySearchTree Примечание: некоторые сообщения были упрощены; перекомпилируйте с помощью -Xdiags:verbose, чтобы получить полный вывод 1 ошибка
Подробное сообщение об ошибке:
BinarySearchTree.Ява:132: ошибка: не найден подходящий метод для вставки(инт) вставки(г); Способ ^ BinarySearchTree.вставка(Т) не применим (несоответствие аргумента; int не может быть преобразован в T) метод BinarySearchTree.вставка(Т,BinaryNode) не применим (фактические и формальные списки аргументов различаются по длине), где T-это тип переменной: Т простирается сопоставимых<? super T> объявлено в классе BinarySearchTree 1 ошибка
Вот мой код:
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
public class BinarySearchTree<T extends java.lang.Comparable<? super T>>
{
private static class BinaryNode<T>
{
private T element; // The data in the node
private BinaryNode<T> left; // Left child
private BinaryNode<T> right; // Right child
// Constructors
BinaryNode( T theElement )
{
this( theElement, null, null );
}
BinaryNode( T theElement, BinaryNode<T> lt, BinaryNode<T> rt )
{
element = theElement;
left = <
right = rt;
}
}
private BinaryNode<T> root; //root node of the tree
// Constructor
public BinarySearchTree( )
{
root = null;
}
/***************************************************
* FUNCTION isEmpty: isEmpty *
* checks if the tree is empty *
* INPUT PARAMETERS: none *
* none *
* OUTPUT: boolean *
* true if the tree is empty, false otherwise *
****************************************************/
public boolean isEmpty( )
{
return root == null;
}
private BinaryNode<T> findMin( BinaryNode<T> t )
{
if( t == null )
return null;
else if( t.left == null )
return t;
return findMin( t.left );
}
/***************************************************
* FUNCTION insert: insert *
* inserts an item into the tree *
* INPUT PARAMETERS: x *
* x - the item to be added to the BST *
* OUTPUT: none *
* none *
****************************************************/
public void insert( T x )
{
root = insert( x, root );
}
/***************************************************
* FUNCTION insert: insert helper method *
* inserts an item into the tree *
* INPUT PARAMETERS: x, t *
* x - the item to be added to the BST, subtree to be inserted in *
* OUTPUT: BinaryNode<T> *
* node to be set *
****************************************************/
public BinaryNode<T> insert( T x, BinaryNode<T> t )
{
if( t == null )
return new BinaryNode<T>( x, null, null );
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
{
t.left = insert( x, t.left );
}
else if( compareResult > 0 )
{
t.right = insert( x, t.right );
}
else
; // Duplicate; do nothing
return t;
}
/***************************************************
* FUNCTION insertList: Option 1 *
* parses a string and insert the values contained in it *
* INPUT PARAMETERS: csv *
* csv - comma seperated list of integers *
* OUTPUT: none *
* none *
****************************************************/
public void insertList(String csv)
{
String[] inputValues = csv.split(",") ; // Numbers are seperated by comma as instructed
for (String x : inputValues)
{
int y = Integer.parseInt(x);
insert(y);
}
}
}
Ответ №1:
У вас есть общий параметр, поэтому логически правильно создавать новое дерево при чтении CSV.
Это также означает insertList(...)
, что он должен стать статическим и теперь вызываться как BinarySearchTree<Integer> tree = BinarySearchTree.insertList(...)
Вот код:
public static void insertList(String csv)
{
String[] inputValues = csv.split(",") ; // Numbers are seperated by comma as instructed
BinarySearchTree<Integer> tree = new BinarySearchTree<>();
for (String x : inputValues)
{
int y = Integer.parseInt(x);
tree.insert(y);
}
}