Альтернативный способ сделать это без LinkedList? - PullRequest
2 голосов
/ 01 мая 2020

Моя IDE предложила использовать LinkedList, поэтому он автоматически импортировал его в мой код. Но есть ли способ добиться того же, но без импорта LinkedList и использования только ArrayList? Видимо, это возможно, но я понятия не имею, как.

/**
 * Search this Twitter for the latest Tweet of a given author.
 * If there are no tweets from the given author, then the
 * method returns null.
 * O(1)
 */
public Tweet latestTweetByAuthor(String author) {
    //getting hashvalue for the date
    int hashValue = tweetsByAuthor2.hashFunction(author);

    //getting all the hashtable buckets
    ArrayList<LinkedList<HashPair<String, Tweet>>> allBuckets = tweetsByAuthor2.getBuckets();

    //if buckets at hashvalue == null
    if (allBuckets.get(hashValue) == null) {
        return null;
    } else {
        return allBuckets.get(hashValue).get(allBuckets.get(hashValue).size() - 1).getValue();
    }
}

Ответы [ 3 ]

1 голос
/ 01 мая 2020

Вы можете, но вы также должны изменить tweetsByAuthor2.getBuckets() тип возврата на ArrayList<ArrayList<HashPair<String, Tweet>>> getBuckets(). Кроме этого вы не используете какую-либо конкретную c функциональность LinkedList. Только здесь allBuckets.get(hashValue).get(allBuckets.get(hashValue).size() - 1) Я вижу, что вы используете LinkedList.get(). ArrayList также имеет тот же метод.

Кроме того, общий совет, если возможно, использовать интерфейсы, а не реализации. Так что ваш tweetsByAuthor2.getBuckets() будет выглядеть так: List<List<HashPair<String, Tweet>>> getBuckets(). Таким образом, вам даже не нужно заботиться о том, какая реализация используется.

Например, проверьте этот ответ stackoverflow для преимуществ использования интерфейсов в качестве типа возврата

1 голос
/ 01 мая 2020

Если вы используете Java 10 или более поздние версии, вы можете использовать ключевое слово var для сложных типов переменных для ясности.

/**
 * Search this Twitter for the latest Tweet of a given author.
 * If there are no tweets from the given author, then the
 * method returns null.
 * O(1)
 */
public Tweet latestTweetByAuthor(String author) {
    //getting hashvalue for the date
    int hashValue = tweetsByAuthor2.hashFunction(author);

    //getting all the hashtable buckets
    var allBuckets = tweetsByAuthor2.getBuckets();

    //if buckets at hashvalue == null
    if (allBuckets.get(hashValue) == null) {
        return null;
    } else {
        return allBuckets.get(hashValue).get(allBuckets.get(hashValue).size() - 1).getValue();
    }
}
1 голос
/ 01 мая 2020

Вы можете попробовать это

   public Tweet latestTweetByAuthor(String author) {
        // getting hashvalue for the date
        int hashValue = tweetsByAuthor2.hashFunction(author);

        // getting all the hashtable buckets
        ArrayList<ArrayList<HashPair<String, Tweet>>> allBuckets = tweetsByAuthor2.getBuckets();

        // if buckets at hashvalue == null
        if (allBuckets.get(hashValue) == null) {
            return null;
        } else {
            return allBuckets.get(hashValue).get(allBuckets.get(hashValue).size() - 1).getValue();
        }
    }
...